为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 2021-09-17 12:58:32
我正在尝试在我的 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 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

解决了,我觉得很愚蠢。

作为 Axios 的新手,我从字面上复制了代码。示例 Axios 代码用于 POST。我突然意识到通过bodyParameters. 删除它和 GET 工作!

顺便说一句,我希望这对将来的其他人有所帮助,在 Auth Token 前面加上“Bearer”是完全可选的。这两个工作正常:

  headers: { Authorization: "Bearer " + authToken}

  headers: { Authorization: authToken}


查看完整回答
反对 回复 2021-09-17
  • 2 回答
  • 0 关注
  • 773 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信