Search code examples
node.jsexpressputbody-parser

NodeJS/Express: PUT and body parser, body object empty


I write a simple rest api for a blog. I have the following code (main file):

var port = process.env.PORT || 8080; 
var express = require('express'); 
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var database = require('./config/database');
var app = express(); 
mongoose.connect(database.url);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); 
app.use(express.static('public'));

mongoose.connection.once('open', function () {
    console.log('database connection established');
});

// Routes
app.use('/api/blog', require('./routes/blogroutes.js').router); 

// Start
app.listen(port, function () {
    console.log('listening on port ', port); 
}); 

The file blogroutes.js looks like the following (extract):

var express = require('express');
var router = express.Router(); 

var BlogEntry = require('../models/blogEntry');

router.use(function (req, res, next) {
    next();
});

router.route('/entry/:year/:month/:day/:nr')
    //.get(...).delete(...)
    .put(function (req, res) {
        console.log(req.body); 
    });

router.post('/entry', function (req, res) {
    console.log(req.body); 
}); 

module.exports = {router: router}; 

The problem now is the following: When I call in the PowerShell curl -uri http://localhost:8080/api/blog/entry/2016/3/2/3 -method put -body @{title='my first entry';text='Lorem ipsum'}, the console output is {}. When I call in the PowerShell curl -uri http://localhost:8080/api/blog/entry -method post -body @{title='my first entry';text='Lorem ipsum'}, the console output is as expected { text: 'Wonderful', title: 'My second bike trip' }. Do you have any idea why and how can I access the put body?


Solution

  • Since it doesn't look like you're using real cURL, but instead it seems to be something like Powershell's Invoke-WebRequest cmdlet, the documentation for Invoke-WebRequest specifically mentions that the Content-Type of application/x-www-form-urlencoded will only be sent for POST requests. So you will need to explicitly set the Content-Type for non-POST requests by specifying an additional command-line option: -ContentType "application/x-www-form-urlencoded".