Trying 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();

myagent
  .post('http://localhost/endpoint')
  .set('api_key', apikey)
  .set('Content-Type', 'multipart/form-data')
  .send(fields)
  .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()?

Thanks!

Try .type('form') instead of .set('Content-Type', 'multipart/form-data')

See http://visionmedia.github.io/superagent/#setting-the%20content-type

It is not clear what is in the fields variable that you are sending, but here is some information that may help you determine where your problem lies.

To begin with, if you are actually trying to build a multi-part request, this is the official documentation for doing so: http://visionmedia.github.com/superagent/#multipart-requests

as for the error that you got...

The reason is that during the process of preparing the request, SuperAgent checks the data to be sent to see if it is a string. If it is not, it attempts to serialize the data based on the value of the 'Content-Type', as seen below:

exports.serialize = {
  'application/x-www-form-urlencoded': qs.stringify,
  'application/json': JSON.stringify
};

which is used here:

// body
if ('HEAD' != method && !req._headerSent) {
  // serialize stuff
  if ('string' != typeof data) {
    var serialize = exports.serialize[req.getHeader('Content-Type')];
    if (serialize) data = serialize(data);
  }

  // content-length
  if (data && !req.getHeader('Content-Length')) {
    this.set('Content-Length', Buffer.byteLength(data));
  }
}

this means that to set a form 'Content-Type' manually you would use

.set('Content-Type', 'application/x-www-form-urlencoded')

or

.type('form') as risyasin mentioned

any other 'Content-Type' will not be serialized, and Buffer.byteLength(data) will subsequently throw the TypeError: Argument must be a string exception if the value of your fields variable is not a string.