簡體   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