繁体   English   中英

在客户端的 XMLHttpRequest 之后,如何在服务器端获取 FormData 值?

[英]How do I get FormData values in Server-side after XMLHttpRequest in client-side?

我正在构建一个单页应用程序,用户可以在其中上传要批准或拒绝的图片。

上传图片后,用户可以go到待处理区批准或拒绝该照片。

如果用户拒绝照片,他必须从下拉菜单中提供原因。

当我在客户端提交 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) 时,我不断收到 {}。 请帮忙。

为了访问你必须解析它的主体,你应该使用 bodyParser

步骤1

安装bodyParser

$ npm install body-parser

第2步

在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM