我正在使用body-parser npm包来解析Application / JSON格式的POST数据,并使用一些不同的快速路由器来模块化我正在创建的路由。这是我的主要server.js文件中的重要信息:

server.js

var express = require('express');
var bodyParser = require('body-parser');

app.use(bodyParser.json());

// I'm using a sessionId to identify a person in this dummy app instead of adding in authentication. So the API call is sent to http://localhost:5000/johndoe/todo
app.use('/:sessionId/todo', require('./routes/todoRoutes'));

var port = process.env.PORT || 9191;
app.listen(port, function () {
    console.log('Express server listening on port ' + port);
});


todoRoutes.js:

var todoRouter = require('express').Router();

todoRouter.post('/', function (req, res) {
    console.log("This is the post data:");
    console.log(req.body);
});

module.exports = todoRouter;


req.body似乎通过中间件迷路了;它将{}记录到控制台。但是,我一时兴起将以下内容添加到我的主体中server.js中的解析中间件:

app.use(bodyParser.json(), function (req, res, next) {
    next();
});


现在,它将req.body传递给todoRoutes.js。 (它现在将{title: 'Testing'}等记录到控制台,就像我需要的那样。)

这里发生了什么?构造此结构以便按预期方式工作的最佳方法是什么?我是Express的新手,所以我承认我可能在构造所有错误。

最佳答案

gh,没关系。我是个白痴,发现在Postman中关闭了application / JSON的Content-Type Header(阅读:我必须在某个时候将其关闭),因此bodyParser从未使用过。

该死

感谢您的答复!

关于javascript - 通过Express中间件将req.body传递到路由,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33877320/

10-09 20:34
查看更多