简体   繁体   中英

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.

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.

How do I parse or get the FormData values submitted on the server side?

This is server side code. I am using 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.

$(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. Please help.

In order to access the body you have to parse it, you should bodyParser .

Step 1

install bodyParser

$ npm install body-parser

Step 2

Use it in app.js as following:

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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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