【问题标题】:Can't get nodeJS Express post to display body data无法获取 nodeJS Express 帖子以显示正文数据
【发布时间】:2018-04-11 16:39:13
【问题描述】:

我觉得我已经尝试了所有方法,希望能以新的眼光来看待我的问题。正如标题所示,我正在向运行 express 的 NodeJS 服务器发送一个 http post 请求,并且 nodeJS 将 req.body 返回为未定义/空。

NodeJS 快速代码:

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)
});

【问题讨论】:

    标签: node.js express http-post httprequest


    【解决方案1】:

    你必须使用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

    【讨论】:

    • 我确实试过了,我的控制台日志只吐出:{}
    • 没关系,谢谢。我忘记在 http 请求中添加内容类型。响应非常受欢迎。
    【解决方案2】:

    如果你用的是最新的express,其实可以用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 }`));
    

    由于大众需求,Express 现在默认捆绑 body-parser。

    【讨论】:

    • 试过这个,控制台日志只吐出:{}
    • 没关系,谢谢。我忘记在 http 请求中添加内容类型。响应非常受欢迎。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2016-08-27
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    相关资源
    最近更新 更多