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

Incorporate an id attribute within a Vue template

Adding id elements to the following VUE templates is something I am interested in doing. This way, I can easily identify these html elements by their ids. In the first scenario, my goal is to add an id to the submit (ok) button: <core-dialog v-if ...

"Utilizing PHP with FTP and AJAX, or other comparable technologies

After successfully creating a PHP class for FTP server interaction (connecting, changing directories, uploading files, etc.), I am now eager to provide real-time updates to users about the actions happening on the server. For example, notifying them with m ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Tips for incorporating a hyperlink into a Vuikit table using Vue.js

I've exhausted all my options trying to make this work, and I'm on the verge of removing Vuikit... All I want is to pass dynamic data to the component, create a new HREF with that data, and have a clickable LINK text element displayed :) Here&a ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Creating a text field in an input box using JavaScript or jQuery to input data

At work, I need to use a web application that requires me to fill in two input fields. However, when I try to do so using JavaScript commands, the strings appear but the "Add" button remains disabled. Additionally, even if I enable the button, the data can ...

Is there a way in MVC3 / .net4 to convert a JSON formatted JavaScript array into a C# string array?

I am facing a challenge with my MVC3/.Net service where it is receiving arguments in the form of a JSONified Javascript array. I want to convert them into a C# array of strings. Is there a built-in solution available for this task, or do I need to create ...

Trouble with CSS transitions not functioning while altering React state

Each time a user clicks on an accordion, the content should smoothly show or hide with a transition effect. However, the transition only seems to work when opening a closed accordion, not when closing an already open one! To get a clearer idea of this iss ...

End of container Bootstrap 4 row with two columns at the edge

I'm currently working on an angular project with bootstrap 4. Within the container, there are two rows. I specifically want one row to always be positioned at the bottom of the container. Despite trying methods like justify-content: flex-end;, botto ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

Oops! There seems to be an error with the <path> attribute. It looks like we were expecting a number, but received something different: "

I'm currently working on creating a basic line graph using d3.js and integrating it into a React component. However, I'm encountering this error: Error: <path> attribute d: Expected number, "MNaN,36.393574100…" Unfortunately, the similar ...

I encountered an issue while attempting to manipulate/retrieve the JSON value using REGEX, resulting in an undefined return

I am attempting to retrieve the currency value from a JSON file and if it is USD, then I want to change it to AUD. When trying to find the currency attribute in the JSON file, it returned 'undefined' as shown below: Code: var datastring = JSON. ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

When utilizing :id with Vue, HTML attributes become hidden from view

I am facing an issue where I need to make HTML elements visible, but they appear invisible upon rendering. Below is my HTML code: <div class="created-links-wrapper" v-for="item in createdUrls" :key="item._id"> <d ...

The form's validation fails to recognize dynamically added input after the initial validation

I am currently working on a form that dynamically adds inputs. Whenever the user selects a different "supplier" from the addMaterialSupplier dropdown, a new input for the price is automatically added. The issue I'm facing is that when I click the bu ...

Enhance your Vuex action types in Typescript by adding new actions or extending existing

I'm new to Typescript and I'm exploring ways to add specific type structure to all Actions declared in Vue store without repeating them in every Vuex module file. For instance, instead of manually defining types for each action in every store fi ...