Home > Blockchain >  Why can't I send a form data from axios?
Why can't I send a form data from axios?

Time:12-11

I am consuming an api that asks me to send a filter series within a formData, when doing the tests from Postman everything works without problem, I tried with other libraries and it also works without problem, but when trying to do it from axios the information does not return with the filters.

This is the code I am using:

const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');

let config = {
  method: 'get',
  url: 'https://thisismyurl/filter',
  headers: { 
    'Authorization': 'JWT MYTOKEN', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

CodePudding user response:

You can send Form-data using get method, but the most servers, will reject the form data.

However it is not recommended anymore. The reason is, first because it is visible in the URL and browsers can cache them in it’s history backstacks, and second reason is because browsers have some limitations over the maximum number of characters in url.

If you are to send only few fields/input in the forms you can use it but if you have multiple inputs you should avoid it and use POST instead.

At the end it depends on your own usecase. Technically both GET and POST are fine to send data to server.

replace get with post

const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');

let config = {
  method: 'post',
  url: 'https://thisismyurl/filter',
  headers: { 
    'Authorization': 'JWT MYTOKEN', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
  • Related