繁体   English   中英

为什么 req.body 是一个空的 object?

[英]Why is req.body an empty object?

我正在尝试学习 XMLHttpRequests。 我正在尝试向服务器发送一些输入,但是当它到达那里时,Object 是空的,就像 {} 我注释掉的那个 setRequestHeader,如果它在,object 被正确打印出来,但我得到一个错误应该在浏览器上打开。 但是如果我把它放在 open() 语句之后,它会再次停止工作,并且 object 到达空。 我也尝试过所有这些以及 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>

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

而且,在您的 xhr 调用中,您必须决定要使用什么内容类型来发送数据,必须将数据放入该内容类型,并且您必须适当地设置 header。 然后,您将能够将正确的中间件添加到您的服务器以读取和解析该正文,然后,只有这样,您才能在服务器上的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内容类型数据。

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

尝试设置 header 后调用打开 function

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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