javascript - 可以使用 Postman 访问本地端点,但不能使用 Axios

标签 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-_=.]+

我不明白此错误,因为我已根据此正则表达式检查了身份验证 token 并且它是有效的。

最佳答案

当您引用 authToken 时,它可能仍然是一个 promise ,您可以尝试以下操作:

  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();
  }

关于javascript - 可以使用 Postman 访问本地端点,但不能使用 Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564105/

相关文章:

javascript - 如何在 nginx 后面设置 Phantomjs

node.js - async.<fn>第一次迭代循环后限制停止

c# - 将静态方法与事件处理程序一起使用

javascript - 在 axios 中返回一个对象而不是 null

javascript - Context API 中的 ReactJS 异步 axios

JavaScript 通过另一个函数将对象传递给函数

javascript - 在 PhoneGap 应用程序中从服务器远程显示图像的最佳方式是什么

javascript - 使用 HTML + JavaScript 实现多列组合框

c# - 如何在一段时间后停止异步任务

Firebase Cloud Functions 和 Busboy 不解析字段或文件