首页 > 解决方案 > 获取 API 未发布到 Node.js 服务器(正文为空)

问题描述

我正在尝试使用 fetch() 发布到我正在运行的另一个 Node.js 服务器。当我取出标题时,我的控制台会打印“{}”。当我保留它们时,调用该函数时不会打印任何内容。

我尝试过使用 curl,我也收到了“{}”。

//Server.js (what I am trying to POST to)
var express = require('express');
var app = express();
var PORT = 4000;
app.use(express.json());


app.post('/', function (req, res) {
    console.log(req.body);

})
app.listen(PORT, function () {
    console.log('server running on port: ' + PORT);
})

//Post function (this is inside a separate React component which will perform the POST)
postContents() {
    var data = { username: 'example' };

    fetch('http://localhost:4000/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .catch(error => console.error('Error:', error))
      .then(response => console.log('Success:', JSON.stringify(response)));
  }

标签: javascriptnode.jsreactjsexpressfetch

解决方案


您必须使用 body-parser 作为快速服务器的中间件。

const express = require('express');
const app = express();
const PORT = 4000;
const bodyParser = require('body-parser');
app.use(bodyParser.json());

推荐阅读