How to make both req.files and req.body available in nodejs when the api is sent with axios

Viewed 709

I'm using Axios npm package in my Node.js application which is a built-in microservices architecture. API-gateway is using Axios to call other services.

According to axios documentation, for POST method, request format is like: axios#post(url[, data[, config]]) . means only one argument data.

Can anyone tell me how I can send req.body & req.files data separately to Axios?

2 Answers

According to answer in Axios community to familiar question this could be achieved with the npm package form-data, which simulates WebAPI FormData on the node side.

This would allow you to send files and form fields to the API and receive it in form of multipart form data.

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

const form = new FormData();
// Second argument  can take Buffer or Stream (lazily read during the request) too.
// Third argument is filename if you want to simulate a file upload. Otherwise omit.
form.append('field', 'a,b,c', 'blah.csv');

axios.post('http://example.org/endpoint', form, {
  headers: form.getHeaders(),
})
.then(result => {
  // Handle result…
  console.log(result.data);
});

Bundle your data up as an object, and pass that object through to the axios request as a single payload.

On the other side of the API, you can access the object, and do as you wish.

var payload = { property1: 'values', property2: 'values2' }

now you pass payload around

Related