我試圖發佈數據到我的節點服務器。 數據都聚集在下面的HTMLjquery AJAX發佈formdata到節點,結果爲空req.body
<label for="files" class="col-md-4 control-label">Files</label>
<div class="col-md-7">
<input type="file" id="files" name="files[]" multiple="multiple">
</div>
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-7">
<input id="name" name="name" class="form-control" type="text">
</div>
<label for="url" class="col-md-4 control-label">Landing Page</label>
<div class="col-md-7">
<input id="url" name="name" class="form-control" type="text">
</div>
<button type="button" id="add_files" class="btn btn-primary" style="background-color:#27AE60;">Add Files</button>
click事件被抓的jQuery,併發出了ajax後
$('#add_files').on('click', function() {
var files = $("#files")[0].files;
var name = $("#name").val();
var url = $("#url").val();
var formData = new FormData();
formData.append("name", name);
formData.append("url", url);
$.each($('#files')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '/newData',
type: 'POST',
data: formData, // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType: false
}).done(function() {
console.log("Success: Files sent!");
}).fail(function() {
console.log("An error occurred, the files couldn't be sent!");
});
});
然後後由我的節點服務器,但req.boy抓是空的
app.post('/newData',function(req,res){
console.log("req body ",req.body)
console.log("req body ",req.body.data)
})
所得以下:
req body {}
req body undefined
有什麼想法出了什麼問題?
我的實現是基於以下幾點: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects How can I upload files asynchronously?
'數據:{體:FORMDATA}'...? – davidkonrad
@ davidkonrad,這似乎不是問題。我認爲數據沒有指定就轉到req.body。 – cs04iz1
如果您使用['body-parser'](https://www.npmjs.com/package/body-parser):該模塊不處理您正在使用的'multipart/form-data'。你需要像['multer'](https://www.npmjs.com/package/multer)。 – robertklep