javascript - Node.js req.body is empty when using POST method - Stack Overflow

I'm really new to using REST and Express and I've been following thistutorialon REST API.

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.(StackOverflow wont let me embed more links since i have low reputation points,apologies.) Screenshot of REST easy: .jpg

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.(StackOverflow wont let me embed more links since i have low reputation points,apologies.) Screenshot of REST easy: https://i.sstatic/2C0Jw.jpg

Share Improve this question edited Mar 8, 2017 at 21:17 Raman asked Mar 8, 2017 at 20:31 RamanRaman 882 silver badges8 bronze badges 4
  • Show your result of console.log(req) and console.log(req.body). You may be passing the POST request in wrong format. Make sure the request body is a JSON. You can add the image of the way you are passing the parameters. – rresol Commented Mar 8, 2017 at 20:47
  • How is the POST request being made? – jfriend00 Commented Mar 8, 2017 at 20:56
  • It is probably the way you are doing the POST request to the api then anything else. – nozari Commented Mar 9, 2017 at 1:38
  • Does this answer your question? req.body empty on posts – bunndan Commented May 25, 2021 at 22:31
Add a ment  | 

4 Answers 4

Reset to default 2

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./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"
}

You need enter correct MIME type in the data section on the REST Easy side:

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745667470a4639203.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信