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?
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.
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.
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' .
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.
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'}); };
$(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With