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

后端 未结 4 1777
独厮守ぢ
独厮守ぢ 2021-02-02 11:09

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/         


        
4条回答
  •  感动是毒
    2021-02-02 11:27

    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.

提交回复
热议问题