Node/Express - bodyParser empty for PUT requests
express, node.js, put, rest
Solution
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
Run `express test`
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'});
};
- 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
Problem
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?