空请求正文

4
我已经生成了两个项目,一个使用create-react-app创建,另一个使用express generator创建。
我在本地主机上分别运行这两个项目,第一个运行在localhost:3000端口,第二个运行在localhost:3001端口。
我正在尝试发送POST请求,但是我收到了一个空的req.body响应体。
客户端代码如下:
 handleSubmit(event) {
    event.preventDefault();
    var data = new FormData();
    for (const key of Object.keys(this.state)) {
      data.append(key, this.state[key]);
    }

    const url = "http://localhost:3000/course";
    fetch(url, {
      method: "POST",
      body: this.state
    })
      .then(response => response.text())
      .then(html => console.log(html));
  }

服务器端:

app.js

app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use("/course", course);

router/course.js

router.post("/", function(req, res) {
  if (!req.body) {
    var course = new Course(req.body);
    course
      .save()
      .then(item => {
        res.json({ course: item });
      })
      .catch(err => {
        res.status(500).send("Unable to save to database");
      });
  }
  res.status(200).send("No data to save");
});

1
你在 package.json 中添加了代理吗? "proxy": "http://localhost:3001", - Modig
不,我为什么要这样做呢? - Youssef
2
body: this.state 应该改为 body: data 吧? - Stamos
我尝试了两种方法,但req.body始终为空。 - Youssef
你的React应用如何知道你使用了哪个端口?由于你正在使用create-react-app并且有这个Node后端,你需要设置"proxy": "http://localhost:XXXX"(这是你的Node服务器的端口)。 - Modig
显示剩余5条评论
1个回答

10

body-parser需要设置Content-Type头为'Content-Type': 'application/json'才能知道需要解析的是请求体内容

试着将这段代码添加到请求头中

fetch('http://localhost:3000/course', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接