javascript - Node - Post 请求显示未定义

标签 javascript angularjs node.js angular

我正在制作一个 angular2/Node.js 应用程序。现在,当我尝试从 Node 服务器获取对象时,它返回得很好。但是,当我尝试将数据发布到 Node 服务器时。 request.body 显示未定义。我究竟做错了什么 ?

服务器.js

// Test
router.get('/test', function (req, res) {
    res.json({test:true}); // Works 
});

// Post
router.post('/rest', function (req, res) {
    var body = req.body;
    console.log(body); // Undefined 
    res.json({test:true});
});

app.ts

constructor(private http:Http){
    console.log("Test")
    http.get('/api/User/test').subscribe(result => {
        console.log(result.json());
    });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http.post('/api/User/rest',{test:'Testing req'},{headers:headers})
    .subscribe(result => {
        console.log(result.json());
    });  
}

最佳答案

你安装了body-parser吗?

npm install body-parser --save

在您的路线之前,将其添加到您的快速应用程序中

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

另请参阅:https://github.com/expressjs/body-parser

关于javascript - Node - Post 请求显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399960/

相关文章:

javascript - 使用 jQuery 循环插件作为图像旋转器和寻呼机的问题

html - 如何获得比容器宽但不是全宽的引导容器?

javascript - AngularJS 的 ng-table 重新加载不起作用

node.js - 对于 Bower,在 .bowerrc 中设置目录设置的绝对路径

javascript - 在 ReactJS 的 OnClick 事件中传递 Nav 标签的值或名称

javascript - 使用 jQuery 移动到第 N 个表行

javascript - 如何使用 jQuery 验证插件获取提交按钮的引用?

javascript - AngularJS - ng-repeat,更新尚未定义的模型对象索引

python (django) hashlib vs Nodejs 加密

node.js - 无法在 Node.js Docker 容器中发送 Sentry 事件