BodyParser没有解析所需的数据

时间:2018-08-23 10:32:28

标签: node.js express body-parser

当我使用邮递员发出请求时,正文解析不会传递任何数据。当我使用console.log查看req.body时,它给出了一个空对象。.发生这种情况的任何想法

谢谢

const app = require('express')();
const morgan = require('morgan');
const mongoose = require('mongoose');
const User = require('./models/user');
const bodyParser = require('body-parser');

const uri = 'mongodb://localhost:27017/amazon';



mongoose.connect(uri, function(err) {
    if (err) throw err;
    console.log('Connected to the DB');
})


const port = process.env.PORT || 3000;

// Middlewares
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
    res.json('Hellow');
});

app.post('/create-user', function(req, res, next) {
    console.log(req.body);
    let user = new User();

    user.profile.name = req.body.name;
    user.password = req.body.password;
    user.email = req.body.email;

    user.save(function(err) {
        if (err) return next(err);

        res.json('Successfully created user ' + user.profile.name);
    })
})

app.listen(port, function(err) {
    if (err) throw err
    console.log('Server running');
});

1 个答案:

答案 0 :(得分:0)

邮递员请求应与所附图片相似

Sample

添加Content-Type:“ application / x-www-form-urlencoded”应该可以解决您的问题。