supertest: post(url, data) does not send any data

superagent allows the following syntax:

request(app).post('/url', { foo: 'bar' })

This should set the content-type to json and send the JSON data in the request body.

With supertest the above syntax results in no content-type and no body.

testcase:

  it('.post should work with data', function (done) {
    var app = express();

    app.use(express.bodyParser());

    app.post('/', function(req, res){
      res.send(req.body.name);
    });

    request(app)
    .post('/', { name: 'tobi' })
    .expect('tobi', done);
  })

Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 18
  • Comments: 20 (1 by maintainers)

Most upvoted comments

Adding .type('form') fixed this for me.

This worked for me

import bodyParser from 'body-parser';
app.use(bodyParser.json());

use:

it('.post should work with data', function (done) {
    var app = express();

    app.use(express.bodyParser());

    app.post('/', function(req, res){
      res.send(req.body.name);
    });

    request(app)
    .post('/')
    .send({ name: 'tobi' })
    .expect('tobi', done);
  })

Thanks a lot, mayby fix the Accept POST Header

         testServer
                    .post('/api/book/save/')
                    .type('form')
                    .send(data.book)
                    .set('Accept', /application\/json/)
                    .expect(201)
                    .end(function (err, res) { done(); });

This worked for me

import bodyParser from 'body-parser';
app.use(bodyParser.json());

Nowadays, you should use express.json(), since bodyParser is currently deprecated.

Seems the readme has only this example, which can be very confusing. Related: #168

request(app)
  .post('/')
  .field('name', 'my awesome avatar')
  .attach('avatar', 'test/fixtures/homeboy.jpg')

I didn’t know there is another method:

request(app)
  .post('/api/book/save/')
  .type('form')
  .send(data.book)
  .set('Accept', /application\/json/)
  .expect(201)
  .end(function (err, res) { done(); });

It’s weird that nested form data breaks in .field() .field('name[en]', 'value') does not work, but .send({ name: { en: 'value' } }) works for me. Don’t know why.