我正在构建一个单页应用程序,用户可以在其中上传要批准或拒绝的图片。
上传图片后,用户可以转到待批准区域批准或拒绝照片。
如果用户拒绝了照片,则必须从下拉菜单中提供原因。
当我在客户端提交XMLHttpRequest时,我无法在服务器端获取FormData值。
如何解析或获取在服务器端提交的FormData值?
这是服务器端代码。我正在使用ExpressJS。
// Parse request bodies
app.use(express.urlencoded({ extended: false }));
app.post("/products/approved/:id",async (req,res) => {
console.log(req.body); // I want to get FormData values here
try {
const pId = req.params.id;
await Product.updateone({pId},{status: "approved"});
res.send({message: 'Product has been updated to approved status'});
} catch(e) {
res.send({message: e});
}
});
这是客户端代码。我使用香草JS。
$(rejectInputBtn).on('click',function(e) {
e.preventDefault();
const currentOption = $( "#rejection-select option:selected" ).text();
console.log(currentOption);
if (currentOption === "--Please choose an option--") {
alert('Please select an option!');
return;
}
const id = $(this).parent().parent().parent().find('h2').html();
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('POST',`/products/rejected/${id}`,true);
let formData = new FormData(document.getElementById('myform'));
xhr.send(formData);
xhr.onload = function() {
console.log(this.response);
}
});
当我在服务器端使用console.log(req.body)时,我不断收到{}。请帮忙。