如何 post 使用 axios 使用 api

How to post consume an api with axios

我在 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))
}

最后终于用XMLHttpRequest获取token了。 在进行了大量研究和测试后,我无法使用 Axios、Fetch、AWS-SDK 或 AWS-Amplify 实现它。在浏览 Internet 时,我停在了一个名为 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);
    }
});