简体   繁体   中英

Node.js req.body is empty when using POST method

I'm really new to using REST and Express and I've been following this tutorial on REST API. Here is my app.js code:

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

var app = express();
var port    = parseInt(process.env.PORT, 10) || 3000;

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

Genre = require('./models/genre');

//Connect to mongoose
mongoose.connect('mongodb://localhost/bookstore');

var db = mongoose.connection;

app.listen(port);
console.log('Running on port 3000\n\n');

app.post('/api/genres', function(req, res){
        console.log(req.body);
        var genre = req.body;
        Genre.addGenre(genre, function(err, genre){
            if (err) {
                console.log(err);
                res.send({status: 'something went wrong'});
            }else{
            res.send({status: 'saved'});
            res.json(genre);}
        });
}); 

I'm using Rest Easy on Firefox to check the POST request. The error being generated is "Genre Validation failed" because the body is empty. The schema used for this is defined in the model as:

var mongoose = require("mongoose");

//Genre Schema
var genreSchema = new mongoose.Schema({

    name: {
        type: String,
        required: true
    },
    create_data:{
        type: Date,
        default: Date.now
    }
});

var Genre = module.exports = mongoose.model('Genre', genreSchema);

// add genre
module.exports.addGenre = function(genre, callback){
    Genre.create(genre, callback);
};

I've tried several other popular threads but it still isn't solving the problem. I've tried rearranging the order of how modules are imported and input the data as form using 'application/x-www-form-urlencoded'. Any idea?

Edit : Output of console.log(req.body):

{}

Output of console.log(req) is at jbkb1yxa on jsfiddle.net.(StackOverflow wont let me embed more links since i have low reputation points,apologies.) Screenshot of REST easy: http://imgur.com/6QmQqRV

In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.

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

See https://github.com/expressjs/body-parser

The 'body-parser' middleware only handles JSON and urlencoded data

In Postman, to test HTTP post actions with a raw JSON data payload, select the raw option and set the following header parameters:

Content-Type: application/json

Also, be sure to wrap any strings used as keys/values in your JSON payload in double quotes.

The body-parser package will parse multi-line raw JSON payloads just fine.

{
    "foo": "bar"
}

您需要在REST Easy端的data部分中输入正确的MIME类型:

application/json

It's likely because your call to the database isn't finding what you are looking for. One HUGE pain point for me when I first started learning Mongoose was that I erroneously expected an empty response to be counted as an err but that is not the case.

What is logged if you put console.log(genre) above your res.send and res.json statements?

Also, just wondering, why are you using res.send followed by res.json ?

Ok. So I guess it was probably an extension issue. I used the same code to send the POST request using POSTMAN in chrome and now it is working just fine. Earlier even Postman was not working but after I configured chrome to not use proxy server, it works just fine.

Thanks everyone for helping me out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM