【问题标题】:How to post consume an api with axios如何使用 axios 发布使用 api
【发布时间】:2021-11-26 03:10:15
【问题描述】:

我正在使用 Vue 应用程序并使用 Axios 进行 api 使用。 我正在尝试使用来自 AWS 的 oauth api 来获取令牌并在其他 api 中使用它。 但是,我在控制台中只收到 400。该 api 在 Postman 中运行良好,所以我真的不知道问题可能是什么。我在这里查看了其他一些问题,但没有任何效果。 这是我的代码。

auth_api() {
    axios
    .post(
    'https://myawssite.amazoncognito.com/oauth2/token',
    {'grant_type':'client_credentials'},
    {headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic 123qwe=='
    }}
    )
    .then(response => (this.token = response))
}

【问题讨论】:

  • 您是否考虑过为此使用 AWS Amplify 库?它有很多工具,也许其中之一可以帮助您处理逻辑
  • 嗨@TristanMüller 感谢您的回复!我去看看。

标签: javascript amazon-web-services vuejs2 axios


【解决方案1】:

最后,我终于用 XMLHttpRequest 来获取令牌了。 经过大量研究和测试后,我无法使用 Axios、Fetch、AWS-SDK 或 AWS-Amplify 实现。当我浏览互联网时,我停在了一个名为https://reqbin.com/ 的网页上。有一些使用 XMLHttpRequest 的 post 请求示例,所以我尝试了一下,然后一切正常。

let globalToken; // I declared this outside the export default.

// This is in my created() function.
const loginUrl = 'https://myawssite.amazoncognito.com/oauth2/token'
let xhr = new XMLHttpRequest();
xhr.open('POST', loginUrl);
xhr.setRequestHeader('Authorization', 'Basic 123qwe==');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
    if(xhr.readyState === 4) {
        console.log(xhr.status);
        globalToken = JSON.parse(xhr.responseText);
        console.log(globalToken);
        console.log(globalToken.access_token);
    }
}
xhr.send('grant_type=client_credentials')

为了补充主要答案,对于我需要使用的 API,我使用了 Superagent 库(Axios 和其他人再次让我失望了,或者我只是一个白痴 xD)。在这种情况下,XMLHttpRequest 不起作用。

import superagent from 'superagent'

// This function is in my methods component.
let login = globalToken;
console.log('token is: ', login.access_token);
const apiUrl = 'https://myawssite.execute-api.us-east-1.amazonaws.com/dev/test';
superagent
.post(apiUrl)
.send({ rut: this.rut})
.set('X-Api-Key', 'QWE123')
.set('Authorization', 'Bearer ' + login.access_token)
.end((err, res) => {
    if (err) {
        console.log(err);
    } else {
        console.log('rut: ', this.rut);
        console.log(res.text);
    }
});

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2021-03-13
    • 2018-08-31
    • 2018-10-13
    • 1970-01-01
    • 2020-05-18
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多