Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Express - bodyParser empty for PUT requests

I'm getting an error with Express in bodyParser is failing to parse any PUT requests... my config is set up like so:

 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.query());
 app.use(app.router);

However everytime I make a PUT request to an endpoint, req.body returns as 'undefined'.

I've tried making request through Chromes REST console, and also via jQuery ajax requests like so:

 $.ajax({
     url: 'https://localhost:4430/api/locations/5095595b3d3b7b10e9f16cc1',
     type: 'PUT',
     data: {name: "Test name"},
     dataType: 'json'
 });

Any ideas?

like image 700
leepowell Avatar asked Nov 28 '12 10:11

leepowell


People also ask

What does bodyParser do in express?

Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body.

Is bodyParser included in express?

The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.

What is bodyParser limit?

limit. Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb' .

What is bodyParser Urlencoded in node JS?

urlencoded() Function. The express. urlencoded() function is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.


1 Answers

You also need to set the Content-Type to application/json. Your jQuery request should be:

$.ajax({
     url: 'https://localhost:4430/api/locations/5095595b3d3b7b10e9f16cc1',
     type: 'PUT',
     contentType: 'application/json',
     data: JSON.stringify({name: "Test name"}),
     dataType: 'json'
 });

Otherwise, the body parser won't attempt to parse the body.

EDIT: here is my test code

  1. Run express test

  2. Add a /test route in app.js:

app.all('/test', routes.test);

and routes/index.js:

exports.test = function (req, res) {
  console.log(req.body);
  res.send({status: 'ok'});
};
  1. Link jQuery and the following script in index.jade:
$(function () {
  $('#test').click(function () {
    $.ajax({
      url: '/test',
      type: 'PUT',
      contentType: 'application/json',
      data: JSON.stringify({name: "Test name"}),
      dataType: 'json'
    });
  });
});

When I run this, I get the following log:

Express server listening on port 3000
GET / 200 26ms - 333
GET /stylesheets/style.css 304 2ms
GET /javascripts/test.js 304 1ms
{ name: 'Test name' }
PUT /test 200 2ms - 20
like image 64
Laurent Perrin Avatar answered Sep 18 '22 00:09

Laurent Perrin