When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API.

The following code snippets attempt to achieve this:

// Attempt # 1
let res = await axios.post(
    url, {
      "username": args.username,
      "password": args.password
    }).then(res => { console.log(res) })

// Attempt # 2
var params = new FormData()  // requires npm install form-data
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
    url, params
    }).then(res => { console.log(res) })
    
// Attempt # 2a
var params = new FormData()  // requires npm install form-data
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
    url, params, {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }
    }).then(res => { console.log(res) })

// Attempt # 3
var params = new URLSearchParams()  
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
    url, params
    }).then(res => { console.log(res) })

All of the above approaches seem to be sending the post data incorrectly. When inspecting the request using Wireshark, the data seems to be [object Object].

If I make the same call to the API endpoint in Postman and analyze the packet, I see the following format:

Content-Type: multipart/form-data; 
boundary=--------------------------074168144775996161656376
Content-Length: 293
----------------------------074168144775996161656376
Content-Disposition: form-data; name="username"
any.user.name
----------------------------074168144775996161656376
Content-Disposition: form-data; name="password"
MyPassword

Postman provides the expected token as the response in this case.

Is there anyone who can identify why the encoding is failing for these variations? The first approach (#1) follows the axios.post documentation, while the other methods are alternative solutions I have come across. This issue has surfaced as I am transitioning my code to Vue3 from Vue2 where I was successfully using Approach #2 (FormData).

Answer №1

Instead of using Axios, you can achieve the same result with this code:

const args = {
  "username": "someusername",
  "password": "somepassword"
}
const data = {
  "username": args.username,
  "password": args.password
}
const url = "https://google.com"
fetch(url, {
  method: "POST",
  body: JSON.stringify(data)
})

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

Angular: How can objects be efficiently stored in a service for display in the view and use of CRUD functions to interact with the server?

I am exploring different options for creating a service that retrieves relational data from the server. I have two potential approaches in mind, but I am having trouble deciding between them. The first option involves returning the data as a multidimensio ...

Encountered an Unhandled Rejection error in React due to SyntaxError: Unexpected token '<' found in JSON at position

Every time I attempt to access the global variable from a different component, specifically when I try to use it from Brewery.js in Random.js, I encounter the "Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0" error. Brewery. ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

The compatibility issue between Bootstrap4 Navbar and "jQuery.BgSwitcher" is causing functionality limitations on mobile devices

Currently, I am utilizing Bootswatch4 within Bootstrap4 and have a requirement for a div with backgrounds that change or fade. After some research, I stumbled upon a JavaScript solution that aligns closely with my needs at: https://github.com/rewish/jquery ...

Adjusting the dimensions of the box while the clock is ticking

I am looking to automatically resize a cube whenever a new value is entered in the input text box. I have found a similar solution that updates the cube size only when a button is clicked. http://jsfiddle.net/EtSf3/3/ document.getElementById('btn&ap ...

Unable to push information to an Azure SQL Database through Azure Functions

I am facing an issue where I need to add new rows to my Azure SQL Database using an Azure Function. The specific error message that I am encountering is RequestError: Cannot insert the value NULL into column 'OrgName', table 'ICTDatabase.d ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

Is it better to verify the data from an ajax request or allow JavaScript to generate an error if the data is empty

Is it better to check if the necessary data is present when handling success data in jQuery, like this? success: function (data) { if (data.new_rank !== undefined) { $('._user_rank').html(data.new_rank); } } Or should you just l ...

How to retrieve an incorrect index from an array in Vue3?

Working on my task list project, I have an object within my main component structured like this: const tasks = ref([ { name: "Complete homework", completed: false }, { name: "Go for a run", completed: true }, I'm looping throu ...

What could be causing my v-select to be rendered multiple times?

I am currently utilizing vuex and vuetify for my project. I want to create a dropdown list that displays items fetched from my server in the form of a Json object. These objects are returned as an array from my store, which I access using a getter in my co ...

Locate items across three different arrays

Is there a more efficient way to search for an element across 3 arrays and create a string using their values? I have attempted a solution and generated the output, but I am curious if there is a better approach available. var numbers = ['1',&ap ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

Utilize the power of Nuxt and Vue 3 to create sortable columns in a table, with the ability to only change the icons on the sorted column

I am facing a challenge with my sortable table icons. Whenever I click on an icon to sort a column, all the other icons also change direction. I understand that this is happening because I am toggling the visibility of icons based on the currentSortDir sta ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

Filtering text for highlighting in Vue.js is a breeze

Struggling to create a text highlight filter using vuejs. The task involves iterating through an array of words, highlighting any matches with a span and class. However, I'm facing difficulty in getting the data to return with proper HTML formatting i ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

What is the best way to center two items within a border?

Here is the CSS code I wrote to center align my text with a bottom border: .arrow-down { width: 2rem; display: inline; position: absolute; top: -0.6rem; left: 50%; margin-left: -59px; background: $grey_200; z-index: 5; } .showless > se ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...