简体   繁体   中英

multiple asynchronous post request with files in nodejs

I've tried to send a bunch of post requests with file upload in nodejs. using axios.post, I could make a single request easily. But I got an error when trying send multiple asynchronous requests.

Based on the axios document, it uses axios.all([ axios.get(), axios.get(), ...]) to make async requests at time.

If I sent my code, the error says:

"Error: Request failed with status code 500 ~ "

. This error is the same when I send a request without file upload. So I guess my code doesn't attach a file when I send async request.

Please advise me what I am missing.

My code is below:

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('files', fs.createReadStream('./liscense.jpg'));

var config = {
  method: 'post',
  url: 'https://domainname/scan/id',
  headers: { 
    ...data.getHeaders()
  },
  data : data
};

axios
.all([axios(config), axios(config)])
.then(
    axios.spread((res1, res2) => {
        console.log(res1.data, res2.data);
    })
)
.catch((error) => {
  console.log(error);
});

Your problem is that you are sending a empty stream,

There is an "_streams" array in your form data that contains the stream of your "liscense.jpg" file, and when you POST the first request to your target host, this stream will be empty and the stream of your other requests is empty, so the file does not reach your destination.

In short, this code only send your file once in first request, and other requests do not include your file/files.

you can try this:

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

function postRequest() {
    const data = new FormData();
    data.append('files', fs.createReadStream('./liscense.jpg'));
    const config = {
        method: 'post',
        url: 'https://domainname/scan/id',
        headers: {
            ...data.getHeaders()
        },
        data: data
    };
    return config;
}

axios
    .all([axios(postRequest()), axios(postRequest())])
    .then(
        axios.spread((res1, res2) => {
            console.log(res1.data, res2.data);
        })
    )
    .catch((error) => {
        console.log(error);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM