0
votes

I am trying to call post API of aws Cognito (Token endpoint). It is perfectly working in my postman client. But I am facing the issue in my VueJS code.

Below is my code snippet.

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 successfully getting "code" value from Login Endpoint In above code, HTTP is the object imported from other javascript which is 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 am not sure but the issue is that in my postman, I have used 'application/x-www-form-urlencoded' option in body + header. And here i am not able to set this value in body.

I thing my header and 'application/x-www-form-urlencoded' option in body is not getting set properly.

I have tried with {emulateJSON:true} option. But not worked!

I am getting 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":"https://maddox.auth.eu-west-1.amazoncognito.com","url":"https://maddox.auth.eu-west-1.amazoncognito.com/oauth2/token","data":"{\"grant_type\":\"authorization_code\",\"client_id\":\"4jcmshlse80ab667okni41fbf5\",\"redirect_uri\":\"http://localhost:8080/callback\",\"code\":\"e19170dc-3d8f-420e-99b6-c05f7abad313\"}"},"request":{}}

1
You need to stringify your payload using either a simple JSON.stringify or a library like qs.connexo
Tried! But Still the same issue.Jayesh Dhandha

1 Answers

4
votes

The TOKEN Endpoint only accept application/x-www-form-urlencoded and you are sending JSON (because axios only serializes JavaScript objects to JSON)

How to use axios to send application/x-www-form-urlencoded: https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

here is example with 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>