繁体   English   中英

req.body为空的node.js并表达

[英]Req.body is empty node.js and express

我正在尝试从客户端页面向服务器发送字符串,但是服务器接收到一个空对象。 这是我的客户端代码:

fetch("/sugestions/sugestions.txt", {
  method: "POST",
  body: JSON.stringify({ info: "Some data" }),
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
})
  .then(res => {
    if (res.ok) console.log("Yay it worked!");
    else window.alert("Uh oh. Something went wrong!\n" + res);
  });

这是我的服务器端代码:

const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");

const app = express();
const port = process.env.PORT || 8080;

app.set("view engine", "ejs");
app.use(bodyParser());

app.post("/sugestions/*", (req, res) => {
  info = JSON.parse(req.body);
  fs.appendFile(path("req").pathname, info.info, (err) => {
    if (err) res.status(404).end();
    else res.status(200).end();
  });
});

app.listen(port);

如果重要的话,以下是路径函数:

const path = req => url.parse(`${req.protocol}://${req.get("host")}${req.originalUrl}`, true);

要访问请求的正文,您需要使用bodyParser。 并且您需要明确地告诉bodyParser您需要解析的数据格式。 现在进入您的解决方案,更换

app.use(bodyParser());

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

将这两行添加到您的代码中

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

从Express 4.16.0开始,您可以使用app.use(express.json()); 从请求中获取json数据,在您的情况下是这样。您不需要使用bodyparser等等。

const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");

const app = express();
const port = process.env.PORT || 8080;

app.set("view engine", "ejs");
app.use(express.json())// add this line

app.post("/sugestions/*", (req, res) => {
  info = JSON.parse(req.body);
  fs.appendFile(path("req").pathname, info.info, (err) => {
    if (err) res.status(404).end();
    else res.status(200).end();
  });
});

app.listen(port);

暂无
暂无

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

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