我想发送表格。在路由中,当我使用console.log(req.body)时,它会记录{}。服务器看到此请求,bodyparser已正确添加。任何想法有什么问题吗? 我的html
<form class='product' id='add'>
<input type="text" class="input1" name="name" placeholder="name">
<input type="text" class="input1" name="type" placeholder="type">
<input type="text" class="input1" name="producer" placeholder="producer">
<input type="file" class="inputImage" name="image" accept="image/jpeg">
<input type="text" class="input1" name="description" placeholder="description">
<button type='button' class='modify' onclick="product.add()"> Add </button>
</form>
我的前端JS
const product.add = () => {
let data = new FormData(document.getElementById('add'));
ajax(data, 'product/add', result => console.log(result));
}
const ajax = (data, url, callback) => {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback( JSON.parse( this.response ));
}
};
xhttp.open("POST", url, true);
xhttp.send( data );
};
我的路线
router.all('/add', (req, res) => {
console.log(req.body); //here log '{}'
});
答案 0 :(得分:0)
您似乎在表单中包含一个文件,因此请求将作为multipart / form-data发送。 body-parser在其npm页面上明确表示,它们不处理多部分主体。他们推荐了一些模块-我使用formidable
希望这会有所帮助!