简体   繁体   English

Express.js POST req.body 为空

[英]Express.js POST req.body empty

So I have the following code in my server.js file that I'm running with node.js.所以我在使用 node.js 运行的 server.js 文件中有以下代码。 I'm using express to handle HTTP requests.我正在使用 express 来处理 HTTP 请求。

app.post('/api/destinations', function (req, res) {
  var new_destination = req.body;
  console.log(req.body);
  console.log(req.headers);
  db.Destination.create(new_destination, function(err, destination){
    if (err){
      res.send("Error: "+err);
    }
    res.json(destination);
  });
});

I'm running the following in Terminal:我在终端中运行以下内容:

curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations

After running that server.js prints out the following.运行该 server.js 后打印出以下内容。

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }

So req.body is {} .所以 req.body 是{} I read other Stack Overflow posts about similar issues where content-type was not correct because of body-parser.我阅读了其他关于类似问题的 Stack Overflow 帖子,其中由于正文解析器,内容类型不正确。 But that isn't the issue because content-type is application/json.但这不是问题,因为内容类型是 application/json。

Any ideas how to get the actual body of the request?任何想法如何获取请求的实际正文?

Thanks in advance.提前致谢。

You need bodyParser.json as well:您还需要 bodyParser.json:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Sometimes the req.body shows {} if you forgot to put the name attribute to the form input fields.有时,如果您忘记将 name 属性放入表单输入字段,则 req.body 会显示 {}。 Following is an example:下面是一个例子:

<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>

Then the req.body shows { myemail: 'mathewjohnxxxx@gmail.com' }然后 req.body 显示{ myemail: 'mathewjohnxxxx@gmail.com' }

I post this answer because, i have encountered the similar problem and this worked for me.我发布这个答案是因为,我遇到了类似的问题,这对我有用。

Make sure if you are making the form and inputs in javascript that you append the input to the form.确保您在 javascript 中制作表单和输入,将输入附加到表单中。 That was my issue.那是我的问题。

yourForm.appendChild(yourInput);

For me the back end was configured properly the issue was valid JSON format including double quotes on the variables.对我来说,后端配置正确,问题是有效的 JSON 格式,包括变量上的双引号。

this did not work这不起作用

      const res = await axios.post(serverPath + "/user/login", {
         email: email,
         password: password,
      });

This DID work (with double quotes around email and password确实有效(电子邮件和密码周围有双引号

      const res = await axios.post(serverPath + "/user/login", {
         "email": email,
         "password": password,
      });

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

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