Learn the process of sending both Header and Body data in a POST request using Axios with Vue.js

I'm currently attempting to call the post API of AWS Cognito's Token endpoint. The API functions perfectly when tested in my Postman client, but I am encountering issues when implementing it in my VueJS code.

Here is a snippet of my code:

test.vue

<script>
HTTP.post(`token`, {
    'grant_type': 'authorization_code',
    'client_id': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    'redirect_uri': 'http://localhost:8080/callback',
    'code': this.$route.query.code
  })
  .then(response => {
    console.log('Response: ' + response)
  })
  .catch(e => {
    console.log('Error: ' + e)
  })
</script>

I am able to successfully retrieve the "code" value from the Login Endpoint provided by AWS documentation. In the above code snippet, the HTTP object is imported from another JS file as shown below:

http-common.js

import axios from 'axios'

export const HTTP = axios.create({
  baseURL: 'https://maddox.auth.eu-west-1.amazoncognito.com/oauth2/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

I suspect that the issue may lie in the fact that in Postman, I used the 'application/x-www-form-urlencoded' option in both the body and header settings, whereas I am struggling to set this value properly in the body of my current code.

Despite trying out {emulateJSON:true} option, the issue persists!

The error message received states: HTTP Code: 400

{"data":{"error":"invalid_request"},"status":400,"statusText":"Bad Request","headers":{"pragma":"no-cache","content-type":"application/json;charset=UTF-8","cache-control":"no-cache, no-store, max-age=0, must-revalidate","expires":"0"},"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json","Content-Type":"application/x-www-form-urlencoded"},"method":"post","baseURL":"","url":"","data":"{\"grant_type\":\"authorization_code\",\"client_id\":\"4jcmshlse80ab667okni41fbf5\",\"redirect_uri\":\"http://localhost:8080/callback\",\"code\":\"e19170dc-3d8f-420e-99b6-c05f7abad313\"}"},"request":{}}

Answer №1

The TOKEN Endpoint requires data in the format of

application/x-www-form-urlencoded
, but you are sending JSON data (as axios only converts JavaScript objects to JSON)

To use axios for sending

application/x-www-form-urlencoded
data, check out this link: https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

Here is an example using the qs library:

<script>
HTTP.post(`token`, qs.stringify({
    'grant_type': 'authorization_code',
    'client_id': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    'redirect_uri': 'http://localhost:8080/callback',
    'code': this.$route.query.code
  }))
  .then(response => {
    console.log('Response: ' + response)
  })
  .catch(e => {
    console.log('Error: ' + e)
  })
</script>

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

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

Tips for improving the readability of my code

This code snippet pertains to handling a POST request in Express.js with MongoDB integration. router.post('/', function(req, res){ var data = req.body; Tag.find({name: data.name}).limit(1).exec( function(err, result){ if(err) { // ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

Please indicate the generator title (for example, nx generate @nrwl/workspace:library) specifically for Angular

Currently, I am expanding my knowledge in web development. While working with Angular, I encountered an issue when trying to create a new component. The error message reads "Specify the generator name (e.g., nx generate @nrwl/workspace:library)" after exec ...

The authentication process in ExpressJS with Passport.js is failing to return the res.user object in React

I recently followed a tutorial on Medium about implementing Passport js with a MERN stack. While I was successful in getting authentication to work, I am facing challenges with persisting users between routes. Below are excerpts from the code I used: ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

The HTTP request arrives with no content within the body

I am in the process of developing a basic client-server application using Node and Express. The goal is for the program to receive a JSON input on the client-side, perform some operations, and then send data to the server-side. Currently, I am able to sen ...

Saving the information into a designated MongoDB repository with a particular title

One of my recent projects involved creating a script that pulls data from the Binance API and sends it to MongoDB. This script runs every hour using the Node-Schedule package, fetching three different sets of data based on their symbols (BTCUSDT, ETHUSDT, ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

Dealing with TSLint errors within the node_modules directory in Angular 2

After installing the angular2-material-datepicker via NPM, it is now in my project's node_modules folder. However, I am encountering tslint errors that should not be happening. ERROR in ./~/angular2-material-datepicker/index.ts [1, 15]: ' should ...

Language setting required for dijit.form.DateTextBox

I am attempting to create a calendar control dynamically using Dojo 1.5 and set the language to Spanish, but so far I have been unsuccessful. I tried using "lang:es-es" among other things with no success... here is the element: <input type="text" const ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...