How to post multipart/form-data with node.js superagent


I am trying to send the content-type in my superagent post request to multipart/form-data.

var myagent = superagent.agent();

  .set('api_key', apikey)
  .set('Content-Type', 'multipart/form-data')
  .end(function(error, response){
    if(error) { 
       console.log("Error: " + error);

The error I get is: TypeError: Argument must be a string

If I remove the:

.set('Content-Type', 'multipart/form-data')

I don't get any error but my back end is receiving the request as content-type: application/json

How can I force the content type to be multipart/form-data so that I can access req.files()?

7/11/2017 4:18:41 AM

In 2017, do it this way.

First, you do NOT mention either of the following:

.set('Content-Type', 'multipart/form-data')



Second, you do NOT use the .send, you use .field(name, value).

An example

Let's say you wanted to send a form-data request with the following:

  • two text fields: name and phone
  • one file: photo

So your request will be something like this:

  .post( '' )
  .set('Authorization', '...')
  .field('name', 'My name')
  .field('phone', 'My phone')
  .attach('photo', 'path/to/photo.gif')

  .then((result) => {
    // process the result here
  .catch((err) => {
    throw err;

And, let's say you wanted to send JSON as a value of one of your fields, then you'd do this.

  .post( '' )

  .field('data', JSON.stringify({ name: 'value' })   )

  .then( ... )
  .catch( ... )
7/11/2017 4:17:10 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow