What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do it with axios, the information doesn't return with the filters.

Here is the code snippet I am currently 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);
});

Answer №1

When it comes to sending Form-data, you can opt for the get method but it is likely that most servers will reject the form data.

Using this method is no longer recommended due to a couple of reasons. Firstly, because the data is visible in the URL which could potentially be cached by browsers in their history stacks. Secondly, browsers have limitations on the maximum number of characters allowed in a URL.

If your form only requires a few fields/inputs, using the get method might work. However, if you have multiple inputs, it's best to avoid it and use POST instead.

In the end, the choice between GET and POST depends on your specific use case. Both methods are technically fine for sending data to a server.

To utilize the POST method, simply 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);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the Meteor Framework for Application Monitoring

Exploring the potential of utilizing Meteor Framework in a Monitoring Application. Scenario: A Java Application operating within a cluster produces data, which is then visualized by a Web Application (charts, etc.) Currently, this process involves using ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

ERROR: An issue occurred while attempting to resolve key-value pairs

Within my function, I am attempting to return a set of key-value pairs upon promise completion, but encountering difficulties. const getCartSummary = async(order) => { return new Promise(async(request, resolve) => { try { cons ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this: <div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" :value="item.title"> </div> ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

Purge React Query Data By ID

Identify the Issue: I'm facing a challenge with invalidating my GET query to fetch a single user. I have two query keys in my request, fetch-user and id. This poses an issue when updating the user's information using a PATCH request, as the cach ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if today is ...

When the JavaScript string retrieved from the database is null, it will be displayed as an empty string

Currently, my Ajax setup involves querying a database on the server with SELECT someColumn FROM someTable. The returned value of someColumn is then updated on the client side by using $('#someElement').text(someColumn); Everything works perfectl ...

Tips for overcoming the Chrome Extension Error related to the "script-source 'self'" issue

I've been developing a Chrome extension that uses goo.gl to shorten URLs. Here is the code I'm currently working with: $("#ajaxfiller").text(""); //Retrieve entered URL var longUrl = $("#input2").val(); longUrl = '"' + longUrl + &a ...

Ugly consequences arise as Gulp stumbles upon uncharted territory during the uglify

I'm experiencing an issue with my squish-jquery task. Every time I run it, I encounter the following error: Starting 'squish-jquery'... events.js:85 throw er; // Unhandled 'error' event ^ Error at new JS_Par ...

Inconsistent Accuracy of React Countdown Timer

Hello everyone! I'm new to programming and I'm currently working on creating a countdown timer that goes from 3 to 0. The issue I'm facing is that the timer counts down too quickly when rendered on the screen. I've tried adjusting the i ...

Error 404 in NodeJS: Page Not Found

I recently started working with NodeJS to develop an ecommerce application. I have a ready-made design and all the front-end components built using AngularJS code. Everything seems to work fine - when clicking on any menu, the page content changes along wi ...

What are the steps for creating personalized sliders with WordPress?

Seeking guidance on how to code WP Template files to enable control from the WP dashboard for adding or removing slider images. A sample code snippet is provided below. <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indi ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...