node js post request body undefined

时间:2017-07-07 05:46:16

标签: node.js express

我是nodejs的新手。我收到请求但是req.body未定义。请提前帮助谢谢。

这是我的代码

Server.js

var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
db = require('./database/database.js'),
PORT = process.env.PORT || 3000,
router = express.Router();
//Routers
var userActionsRouter = require('./routes/user-actions.js');
var userRouter =        require('./routes/user.js');
var transactionRouter = require('./routes/transaction.js');
//Routes
app.use('/api/v2/user_actions/', userActionsRouter);
app.listen(PORT, function(){
    console.log('We are connected'+PORT);
})

路由文件

var express = require('express'),
router = express.Router(),
userActionController = require('../controllers/user-actions-controller.js'),
app = express();
//Sign-In
router.post('/sign_in', userActionController.signIn);
//Sign-Out
router.post('/sign_out', userActionController.signOut);
module.exports = router;

我的user-actions-controller.js文件

var express = require('express');
bodyParser = require('body-parser');
app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
module.exports.signIn = function(req, res){
 console.log('params: ' + JSON.stringify(req.params));//{}
 console.log('body: ' + JSON.stringify(req.body));// undefined 
 console.log('query: ' + JSON.stringify(req.query));//{}
 console.log("data:" +JSON.stringify(req.data));// undefined
})

1 个答案:

答案 0 :(得分:-1)

使用'content-type';

添加'application/json'
'content-type': 'application/json'