【问题标题】:how to pass Header + Body in POST api using Vue JS-axios如何使用 Vue JS-axios 在 POST api 中传递 Header + Body
【发布时间】:2018-08-05 04:29:50
【问题描述】:

我正在尝试调用 aws Cognito (Token endpoint) 的 post API。它在我的邮递员客户端中完美运行。但我在我的 VueJS 代码中遇到了这个问题。

下面是我的代码 sn-p。

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>

我成功地从Login Endpoint 获得“代码”值 在上面的代码中,HTTP 是从下面的其他 javascript 导入的对象。

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'
  }
})

我不确定,但问题是在我的邮递员中,我在正文 + 标题中使用了 'application/x-www-form-urlencoded' 选项。在这里我无法在正文中设置此值。

我的标题和正文中的“application/x-www-form-urlencoded”选项设置不正确。

我已尝试使用 {emulateJSON:true} 选项。但没用!

我收到 HTTP 代码: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":{}}

【问题讨论】:

  • 您需要使用简单的JSON.stringifyqs 之类的库来对有效负载进行字符串化。
  • 试过了!但仍然是同样的问题。

标签: javascript vue.js axios aws-cognito quasar-framework


【解决方案1】:

TOKEN Endpoint 只接受 application/x-www-form-urlencoded 并且您正在发送 JSON(因为 axios 仅将 JavaScript 对象序列化为 JSON)

如何使用axios发送application/x-www-form-urlencoded:https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

这里是 qs 库的示例

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2019-01-06
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多