简体   繁体   English

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

[英]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

Step 1步骤1

install bodyParser安装bodyParser

$ npm install body-parser

Step 2第2步

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.

相关问题 如何将服务器端ASP XmlHttpRequest代码转换为客户端JavaScript? - How do I convert my server-side ASP XmlHttpRequest code to client-side JavaScript? 服务器端请求和XmlHTTPRequest(客户端)和安全性 - Server-side requests and XmlHTTPRequest (client-side) and security 如何在客户端而不是服务器端将我的哈巴狗文件渲染到 html - How do I render my pug files to html on the client-side instead of server-side 如何将数据从客户端表单输入传输到服务器端Nodejs脚本? - How do I transfer data from a client-side form input to a server-side Nodejs script? 如何清除客户端中的服务器端数据表表行 - How do i clear the server-side datatables table rows in client-side Web应用程序国际化,服务器端还是客户端? - Web Application Internationalization, do it server-side or client-side? 客户端或服务器端处理? - Client-side or server-side processing? 服务器端和客户端JavaScript - Server-side and client-side JavaScript 客户端还是服务器端框架? - Client-side or server-side framework? 在服务器端禁用aspxgridviews,如何在客户端处理? - Disabling aspxgridviews on server-side, how to handle on client-side?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM