What could be causing the compatibility issue between Axios and FormData?

Currently, in my Vue.js project, I am utilizing Axios and FormData to transmit data to a server. Previously, this method worked flawlessly. However, at present, when I attempt to send a formData object, it appears that the data is not being appended as expected:

Example of the mock server response:

https://i.sstatic.net/NnS9c.png

Observations from Chrome developer tools:

https://i.sstatic.net/WzH35.png

(Please note that the content-length shows 2 and the FormData seems to be missing)

    let url = "https://benben.free.beeceptor.com/1"
    const fd = new FormData()
    fd.append('key', 'value')
    return axios.post(url, fd, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })

Steps taken so far:

  1. Reviewed the payload via chrome/firefox/edge dev tools and on the mock server.
  2. Experimented with sending simple JSON instead of FormData which proved successful.
  3. Tested post requests with and without specific headers - no change in results.
  4. Confirmed successful appending of data to FormData (the key-value pair exists).
  5. Explored various Stackoverflow suggested solutions but none have resolved the issue.
  6. Tried updating Axios to the latest version.
  7. Utilized the direct Axios API by passing an object directly to Axios.

Please Note: My requirement for FormData is due to the need to upload a file.

If you require additional code snippets or information, please feel free to ask.

Thank you for your assistance!

Answer №1

I have finally cracked the code - I discovered a solution using the snakecaseKeys library to manipulate the data before transmission. Unfortunately, it appears that this method does not cooperate well with FormData objects.

import snakecaseKeys from 'snakecase-keys'
axios.defaults.transformRequest = [(data) => {
    if (data) {
        return snakecaseKeys(data, { deep: true })
    }
}, ...axios.defaults.transformRequest]

A huge shoutout to everyone who shared their insights!

Answer №2

If you happen to encounter the same problem, a workaround is to avoid the transformations in your transformRequest by utilizing instanceof.

  transformRequest: [
    (data) => {
      if (data instanceof FormData) return data;
      // else, proceed with transforming the data
      return transformedData;
    },
  ],

Answer №3

Is it necessary to include the encType="multipart/form-data" attribute in a form when using React, and potentially in Vue as well?

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

I am having trouble accessing a JSON file using node.js

Hey there, I have the following code snippet in Node.js fs.readFile(file, function(err, obj) { obj.data1.forEach(function(element) { console.log (element.key, element.key1); }); }) I am attempting to display the key and value of all in th ...

Searching for a specific value within a hash in MongoDB

I am working with MongoDB documents formatted like this: { "_id": ObjectId("5406e4c49b324869198b456a"), "phones": { "12035508684": 1, "13399874497": 0, "15148399728": 1, "18721839971": 1, "9831132110 ...

Using JavaScript arrow functions to generate list items and append them to an HTML page

I have some front-end JavaScript code that effectively creates li items in an ol tag from a list of string data. I'd like to condense the code into one line... qelements.map(element => { let litag = document.createElement("li"); litag.innerHTML = ...

Steps for verifying repetitive names in input fields

I am experiencing difficulty trying to implement the same validation across multiple tabs within a form. The validation seems to be working in one tab, but not in the others. The start date must always be before the end date My goal is to validate fields ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

Error: Property "rotation" cannot be redefined

After setting up all the necessary dependencies using npm and bower for a project on a different laptop, I encountered an error when trying to run it locally. The error message reads: Uncaught TypeError: Cannot redefine property: rotation at (line 7542 i ...

Temporary headers are displayed and requests are still awaiting fulfillment

Encountering an issue with vue-resource causing a Provisional headers are shown error on Chrome, whereas jQuery functions seamlessly without any trouble. This problem is specifically observed on Chrome with vue-resource. Reproduction Link Using Chrome ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

Fixed navigation menu at the top of the screen

Can anyone help me with my navbar issue? I want it to stay on top of the page, but there's a huge gap between the top of the page and the nav bar. I've tried running a JS file, but it doesn't seem to fix the problem. Any ideas on how to make ...

"Integrating JavaScript files into HTML using Flask: A step-by-step guide

I have created an HTML page with a JavaScript section where I am importing various other .js files: <script type="module"> import * as THREE from "../build/three.module.js"; import { OrbitControls } from ...

Callback functions in Node.js

I'm struggling to grasp the concept of a callback function. This is new territory for me, so please be patient as I try to learn. To dive in and experiment, I'm attempting to log in to Twitter using zombie.js. Consider the following example: va ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Utilizing GTM to Implement Dynamic Content Deployment

Can you provide guidance on the entire process from creating a Custom HTML Tag in GTM to executing JavaScript for firing dynamic HTML code, such as displaying a div with text or image based on a specific rule like the referral or cookie variable? For exam ...

A step-by-step guide on constructing this JSON using PHP

Having an issue with my PHP code for sending a push notification as my JSON object is not formatting correctly... I am aiming for my JSON to be structured like this: { "to": ["xxx"], "data": { "title": "dw", "body": "dw", ...

Issues occur in React when attempting to load an image using TextureLoader in three.js

I have encountered some difficulties while trying to incorporate three.js into a React project. Despite my efforts, I am unable to successfully load texture images. I have set up my own local server, included a callback method for when loading is finished, ...

Is there a way I can showcase my tags such as "vegan, pasta, etc." using the map feature from Firestore?

Is there a way to display all of my labels like "vegan, pasta, etc." from Firestore using the map function? Currently, I am only able to map out the first object [0]. How can I map out all options instead of just one? Here is an example of what works righ ...

Promises do not yield an array of objects

I am currently working on a project that involves using AngularJS with Firebase. In order to retrieve data from Firebase, I have implemented the following code snippets. Controller.js $scope.load_msg=function(){ $scope.msg=[]; Chat.load_msg($scope.na ...

What steps should I take to ensure my images load properly in my Vue application while utilizing webpack and vue-loader?

Having recently ventured into Vue, I find myself delving into some older code for a Vue application and facing the issue of images not loading onto the page. Despite validating that my component's asset paths are accurate as an extension within my cod ...

Experience screen sharing through WEBRTC without the need for any additional browser extensions

One question that I have is: Is it possible to implement screen sharing that works on a wide range of devices and browsers without the need for plugins or experimental settings? I have searched online and come across some plugins for Chrome, but I am look ...