无法获取nodeJS Express帖子来显示正文数据

时间:2018-04-11 16:39:13

标签: node.js express http-post httprequest

我觉得我已经尝试了所有的东西,会欣赏一些新鲜的眼睛来看待我的问题。正如标题所示,我正在向运行express的NodeJS服务器发送http post请求,nodeJS将req.body返回为undefined / empty。

NodeJS Express代码:

const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;

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.post('/addComment', (req, res) => {
 console.log(req.body);
});

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

Javascript浏览器代码:

let data = {name: 'aName'};

fetch('http://localhost:5000/addComment', {
 method: 'post',
 body: JSON.stringify(data)
});

2 个答案:

答案 0 :(得分:2)

您必须使用body-parser中间件:

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
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.post('/addComment', (req, res) => {
console.log(req.body);
});

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

请参阅body-parser

答案 1 :(得分:1)

如果您使用的是最新的快递,您实际上可以使用do

    const express = require('express');
    const path = require('path');
    const app = express();
    const PORT = process.env.PORT || 5000;

    app.use(express.json()) 
    app.use (express.urlencoded({extended: false}))

    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.post('/addComment', (req, res) => {
       console.log(req.body);
   });

   app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
由于受欢迎的需求,

默认情况下默认捆绑身体解析器。