无法访问服务器端的表单数据

时间:2019-06-03 07:29:25

标签: javascript express xmlhttprequest

我正在从前端发出放置请求,而我一直在使用XMLHttpRequest and FormData API请求,但是服务器端我不会收到像req.params, req.body and req.query一样的任何数据

前端代码

var reportSub = () => {

        var report = document.getElementById('report');

        var formData = new FormData(report)



    let xhr = new XMLHttpRequest();

    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.response)
        }
    }

    var queryString = new URLSearchParams(formData);

    xhr.open("PUT", '/threads/edit', true);
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    xhr.send(queryString)

}
 var reportsub = document.querySelector('#repsub');
 reportsub.addEventListener("click",(e)=>{
        e.preventDefault();

        reportSub();
    })

服务器端代码


router.put('/threads/edit',(req,res)=>{

    let board = req.body.board;
    let id = req.body.id;

    console.log(req.query,req.body)

    Board.findById({_id: ObjectId(id)},(error,data)=>{

      if(error)
          res.send(error)

      if(data!==null){
        data.Reprot = true;
        data.save((error,sd)=>{

          if(error)
              res.send(error)

           res.send(sd);   
        })
      } 
      else{
        res.send({"Error":"Id does not exist "})
      }   
    })
})

有一种解决方案是在url中添加数据,然后再次对每个必须传递的变量和数据进行硬编码。 因此,我想使用FormData接口发送数据。

1 个答案:

答案 0 :(得分:0)

我认为您缺少用于解析FormData请求的库。您还可以使用JSON发送数据,因为它是纯文本的,这将简化解析。一个最小的示例如下所示:

server.js

const express = require("express");
const multer = require("multer");
const upload = multer();
const app = express();

app.use(express.static('public'))

app.post('/data', upload.none(), function (req, res) {
    console.log(req.body.favoriteNumber);
    res.send('42 is the only real choice');
});

app.listen(3000, function () {
    console.log('App listening on port 3000!');
});

public/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form id="textForm">
        <p>Your favorite number:</p>
        <input type="text" value="42" name="favoriteNumber" />
    </form>
    <button id="send">Send</button>
    <script>
        const sendButton = document.getElementById("send");
        const form = document.getElementById("textForm");
        sendButton.addEventListener("click", () => {
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.response);
                }
            }

            const formData = new FormData(form);
            xhr.open("POST", '/data', true);
            xhr.send(formData);
        })
    </script>
</body>

</html>

您不必手动设置标题。它是自动设置的,并且确实包含boundary-在编写应用程序时不知道的参数。标头可能如下所示:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryuzeaYvzY77jzcFeA