[英]How do I get FormData values in Server-side after XMLHttpRequest in client-side?
I am building a Single page Application where a user can upload a picture to be approved or rejected.我正在构建一个单页应用程序,用户可以在其中上传要批准或拒绝的图片。
After a picture is uploaded, the user can go to the pending area to approve or reject the photo.上传图片后,用户可以go到待处理区批准或拒绝该照片。
If the user rejects the photo, he must provide a reason from the drop down menu.如果用户拒绝照片,他必须从下拉菜单中提供原因。
I am unable to get the FormData values on the server side when I submit an XMLHttpRequest on the client side.当我在客户端提交 XMLHttpRequest 时,我无法在服务器端获取 FormData 值。
How do I parse or get the FormData values submitted on the server side?如何解析或获取在服务器端提交的 FormData 值?
This is server side code.这是服务器端代码。 I am using ExpressJS.
我正在使用 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});
}
});
This is the client side code.这是客户端代码。 I use vanilla JS.
我使用香草 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);
}
});
I keep getting {} when I use console.log(req.body) on server side.当我在服务器端使用 console.log(req.body) 时,我不断收到 {}。 Please help.
请帮忙。
In order to access the body you have to parse it, you should bodyParser .为了访问你必须解析它的主体,你应该使用 bodyParser 。
install bodyParser
安装
bodyParser
$ npm install body-parser
Use it in app.js as following:在 app.js 中使用它,如下所示:
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.