【问题标题】:Why is req.body an empty object?为什么 req.body 是一个空对象?
【发布时间】:2022-01-06 21:34:41
【问题描述】:

我正在尝试学习 XMLHttpRequests。我正在尝试向服务器发送一些输入,但是当它到达那里时,对象是空的,例如 {} 我注释掉的那个 setRequestHeader,如果它在,对象会被正确打印出来,但是我得到一个错误,它应该在浏览器上打开。但是如果我把它放在 open() 语句之后,它会再次停止工作并且对象是空的。我也尝试过所有这些以及 JSON.stringfy 在发送变量之前,但它也没有工作。

//server.js
const express = require('express');
const app = express();
const cors =require('cors')

app.use(cors())

app.use(express.urlencoded({extended:true}))

app.post('/frases', function(req, res) {
    console.log(req.body);
    const frase = new phrase(req.body);
    // console.log(frase);
})

app.listen(3000, () => console.log('listening on 3000...'));

//script.js
var form = document.getElementsByTagName('form')[0];

const xhr = new XMLHttpRequest();
// xhr.setRequestHeader('Content-Type', 'application/json');

form.onsubmit = (e) => {
    e.preventDefault();
    const thisName = form.elements[0].name;
    const thisValue = form.elements[0].value;
   
    const frase = {[thisName]:thisValue};
    console.log(frase)
    xhr.open('POST', 'http://localhost:3000/frases');
    xhr.send(frase);

    }; 


<!-- index.html -->
    <form action = "http://localhost:3000/frases" method="post">
        <label for="frasefavorita"> Qual é a sua frase favorita?
            <input id= 'frase' type="text" name="frasefavorita">
            <button id= 'send-frase' type="submit">Enviar</button>
    </form>

【问题讨论】:

    标签: javascript json express post xmlhttprequest


    【解决方案1】:

    req.body 默认为空,因为传入请求的正文默认不被读取。您需要与传入内容类型匹配的中间件才能读取该正文,对其进行解析并将结果放入req.body

    而且,在您的 xhr 调用中,您必须决定要使用什么内容类型来发送数据,必须将数据放入该内容类型,并且您必须适当地设置该标头。然后,您将能够将正确的中间件添加到您的服务器以读取和解析该正文,然后,只有这样,您才能在您的服务器上的req.body 中访问它。

    如果您打算将其作为 JSON 发送,那么您可以在客户端执行此操作以设置 JSON 的内容类型并将数据格式化为 JSON:

    form.onsubmit = (e) => {
        e.preventDefault();
        const thisName = form.elements[0].name;
        const thisValue = form.elements[0].value;
       
        const frase = {[thisName]:thisValue};
        const xhr = new XMLHttpRequest();
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.open('POST', 'http://localhost:3000/frases');
        xhr.send(JSON.stringify(frase));
    
    }; 
    

    然后,在您的服务器上,您可以在 /frases 路由处理程序之前添加此中间件:

    // read and parse incoming JSON request bodies
    app.use(express.json());
    

    这将读取并解析来自您的 Ajax 调用的 application/json 内容类型数据。

    附:我建议你使用fetch() 接口来编写新代码,而不是 XMLHttpRequest API。 fetch() 只是更容易使用和更现代的设计(使用承诺)。

    【讨论】:

    • 解决了!也谢谢你的推荐!! :)
    【解决方案2】:

    调用open函数后尝试设置header

    xhr.open('POST', 'http://localhost:3000/frases');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(frase);
    

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 2021-12-08
      • 2020-09-13
      • 2020-07-11
      • 1970-01-01
      • 2018-02-03
      • 2022-01-23
      • 2019-05-11
      相关资源
      最近更新 更多