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

后端 未结 4 1685
独厮守ぢ
独厮守ぢ 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:16

    First, you do not mention either of the following:

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

    OR

    .type('form')
    

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

    Examples

    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:

    superagent
      .post( 'https://example.com/api/foo.bar' )
      .set('Authorization', '...')
      .accept('application/json')
      .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.

    try {
      await superagent
             .post( 'https://example.com/api/dog.crow' )
             .accept('application/json')
             .field('data', JSON.stringify({ name: 'value' }))
    }
    catch ( ex ) {
        // .catch() stuff
    }
    
    // .then() stuff...
    

提交回复
热议问题