可以使用Postman访问本地终结点,但不能使用Axios访问

时间:2019-08-19 21:22:36

标签: javascript asynchronous axios amazon-cognito

我正在尝试在我的Javascript React应用中使用Axios发出一个简单的GET请求。该请求在Postman上可以很好地工作,但我无法在Axios上使用它。

我尝试了几种不同的代码变体,但是没有用。这是最简单的版本:

  import React, { useEffect } from 'react';
  import { Auth } from 'aws-amplify';

  useEffect(() => {
    const fetchRoles = async () => {
      var authToken;

      Auth.currentSession()
        .then(data => { 
          authToken = data.getAccessToken().getJwtToken();
        })
        .catch(err => console.log(err));

      var config = {
        headers: { Authorization: "Bearer " + authToken}
      };

      var bodyParameters = {
        key: "value"
      };

      axios.get("http://127.0.0.1:5000/accounts/roles", bodyParameters, config)
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });

    fetchRoles();
  }

我每次遇到的错误是:

127.0.0.1 - - [19/Aug/2019 14:12:27] "GET /account_management/roles HTTP/1.1" 401 -
Exception getting user An error occurred (InvalidParameterException) when calling the GetUser operation: 1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [A-Za-z0-9-_=.]+

我不了解此错误,因为我已针对此RegEx表达式检查了Auth Token,并且该令牌是有效的。

2 个答案:

答案 0 :(得分:0)

可能是当您引用它时authToken仍然是一个约定,您可以尝试以下方法吗:

  import React, { useEffect } from 'react';
  import { Auth } from 'aws-amplify';

  useEffect(() => {
    const fetchRoles = async () => {

      try {
        let data = await Auth.currentSession();
        const authToken = await data.getAccessToken().getJwtToken();
       } catch(e) {
        console.log(e)
       }

      var config = {
        headers: { Authorization: "Bearer " + authToken}
      };

      var bodyParameters = {
        key: "value"
      };

      axios.get("http://127.0.0.1:5000/accounts/roles", bodyParameters, config)
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });

    fetchRoles();
  }

答案 1 :(得分:0)

解决了这个问题,我感到哑巴。

作为Axios的新手,我从字面上也复制了代码。 Axios示例代码用于POST。我突然意识到,通过bodyParameters发送有效载荷是没有意义的。删除它,GET起作用了!

顺便说一句,希望以后对其他人有帮助,在Auth Token前面加上“ Bearer”是完全可选的。两者都可以正常工作:

  headers: { Authorization: "Bearer " + authToken}

  headers: { Authorization: authToken}
相关问题