Question

I'm creating an API using Express 4.0.0 and one of the routes takes a POST. Currently I'm just trying to have it echo a name sent in the request parameters. The response is a JSON object, but the request expects form fields.

users.post '/user', (req, res) ->
    res.json name: req.params.name

My test sets the type() to form which should allow send() to pass the hash as POST parameters/fields.

describe 'POST /user', ->
    it 'should echo the name sent', (done) ->
        request app
        .post '/user'
        .type 'form'
        .send name: 'Foo'
        .expect '{"name":"Foo"}'
        .end done

Regardless, my test fails and in Express, my req.params is empty, req.param('name') comes up undefined and req.body is also empty.

Is there some req.fields attribute I'm not aware of, or is my test flawed somehow?

Was it helpful?

Solution

tl;dr: You need to parse the body to get that, you can do app.use(require('body-parser')()) and then change your code with name: req.param('name').

So express(and actually node.js http server) will call the request call whenever a http request header have been received and not the body of the request. You have to explicitly read and wait for the body to come and parse it yourself.

Luckily there are express middleware modules that parses the body for you. In this case you are sending a urlencoded/form body, so you need to parse it as such. Use any of these modules according to their examples:

Assuming you use body-parser, then if you want it to parse the body for all routes then just do app.use(require('body-parser')(). If you want it to parse the body for a particular route then do this:

bodyParser = require('body-parser')()
app.post '/user', bodyParser, (req, res) ->
    res.json name: req.param('name')

Once you got the body parsing right, then you can access it either through req.body(for example req.body.name) property or req.param function(for example req.param('name')). The latter will also search through query string and url parameters.

Note that if you want to parse a body with attached files(for uploading files) you need a multipart parser and not just a urlencoded one:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top