Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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()?

like image 299
nwkeeley Avatar asked Dec 13 '12 17:12

nwkeeley


People also ask

How does superagent send form data?

Sending it with superagentsuperagent. post('/some-url/') . send(formData) . end(function(err, response) { //upload done! });

What is superagent in Nodejs?

SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node. js!

How do I submit a supertest in formData?

You can use . attach() method of supertest to send your file to the server.

How do you set a superagent header?

Here is a basic code: const superagent = require('superagent'); superagent. get('https://api.arabam.com/pp/step') . query({ apikey: '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==' }) .


2 Answers

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... 
like image 145
treecoder Avatar answered Oct 05 '22 23:10

treecoder


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

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

like image 20
risyasin Avatar answered Oct 06 '22 01:10

risyasin