为什么使用body解析器来定义req.body?

时间:2018-03-11 10:16:02

标签: javascript jquery node.js mongodb express

我正在提出post请求,但我得到req.bodyundefined。 这是我的sever.js文件

import express from 'express';
import bodyParser from 'body-parser'
import mongoose from 'mongoose'

var db = mongoose.connect('mongodb://localhost:27017/hockey');
var playerModel = require('./model/players')

var app = express();
var port = process.env.port || 3000;
var appRouter = express.Router();
app.use('/api', appRouter);
app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());
appRouter.route('/player')
    .post((req, res) => {
    // undefined why ?
    console.log(req.body);
        var player = new playerModel(req.body);
       // player.save();
        res.status(201).send(player);
    })
    .get((req, res) => {
        playerModel.find((err, player) => {
            if (err) {
                console.log(err);
            }
            else {
                res.json(player);

            }
        })
        // res.json({"name": "nave"})
    })


app.get('/', (req, res) => {
    res.send("helo")
})

app.listen(port, () => {
    console.log('listening to port', port)
});

的package.json

{
  "name": "Mongos",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "babel server.js -o index.js && node index"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongoose": "^5.0.9"
  }
}

当我使用postman并发送帖子请求时,它会显示undefined

enter image description here

Model.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var playerModel = new Schema({
    name: {type: String},
    lastname: {type: String}
})

module.exports = mongoose.model('players', playerModel);

2 个答案:

答案 0 :(得分:3)

请注意中间件的顺序:

app.use('/api', appRouter);
app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

中间件加载的顺序很重要:首先加载的中间件函数也会先执行。

移动app.use('/api', appRouter);,如下所示:

app.use(bodyParser.urlencoded({ extended: true }));    
app.use(bodyParser.json());

app.use('/api', appRouter);

答案 1 :(得分:2)

为了进一步添加到Aleksey的答案,您告诉app通过正文解析器中间件将所有请求传递给app,而不是appRouter,这是处理的内容/ api / player发帖请求。

Aleksey的答案很棒,另一种方法可能就是appRouter使用body-parser

app.use('/api', appRouter);
appRouter.use(bodyParser.urlencoded({ extended: true }));    
appRouter.use(bodyParser.json());

详细了解如何使用Express Middleware