【问题标题】:JWT authorization using Axios post request使用 Axios 发布请求的 JWT 授权
【发布时间】:2020-02-11 15:35:54
【问题描述】:

我收到了一个存储在本地的 JWT。使用相同的 JWT,我正在尝试发出 POST 请求,但是我收到 401 错误,以及显示“未提供 JWT”的错误。我知道 JWT 是有效的,因为我已在 GET 请求中成功使用它。

axios
    .post("https://example.com", {
      headers: {
        token:
          "abc"
      },
      solutions: {
        solution: answer
      }
    })
    .then(response => {
      console.log(response.data);
    })
    .catch(error => {
      console.log(error.response);
    });
};

编辑: 我正在为我的 GET 请求添加代码作为参考。

axios
  .get("https://example.com", {
    headers: {
      token:
        "abc"
    }
  })
  .then(function(response) {
    // makeResponse(response.data);
    console.log(response.data);
  })
  .catch(function(error) {
    console.log(error);
  });

谢谢!

【问题讨论】:

  • headers: { token - 服务器是否在名为令牌的标头中查找 JWT?服务器是你的服务器吗?
  • @Bravo 服务器确实在称为令牌的标头中查找 JWT。这不是我的服务器,而是商业服务器。我使用相同格式发出 GET 请求并获得成功,但我的 POST 请求不起作用。
  • 那么,您已经使用 token 标头中的 JWT 令牌发出了 GET 请求,而这正是 GET 请求需要的地方?
  • @Bravo 是的,没错。我使用的 API 指定我需要为每个请求附加一个 JWT 到一个名为“token”的标头。

标签: javascript rest post jwt


【解决方案1】:

您的 axios.post 可以接受 3 个参数。第一个是端点,第二个是有效负载,第三个是配置或存储令牌的位置。

axios.post(endpoint, payload, config)

我认为您的设置顺序错误:

axios
    .post("https://example.com", {
      headers: {
        token:
          "abc"
      },
      solutions: {
        solution: answer
      }
    })

这应该是:

axios
    .post("https://example.com", 
      solutions: {
        solution: answer
      },
      {
         headers: {
           token: "abc"
         }
      }
     )

【讨论】:

  • 是的,这是我的问题。谢谢!
猜你喜欢
  • 2020-01-19
  • 2021-01-09
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2021-09-09
  • 2011-01-02
  • 1970-01-01
相关资源
最近更新 更多