【问题标题】:React Axios getting reauthorized with JWT token authenticationReact Axios 使用 JWT 令牌身份验证重新授权
【发布时间】:2019-12-18 14:36:08
【问题描述】:

我正在尝试在 React 中使用 Axios 发出发布请求,但我收到了未经授权的错误:

我有一个 API 叫做:

12.0.0.1:8000/api

我正在尝试使用 Axios 发出发布请求,因为我正在使用此代码:

  authenticate(signInForm)
    .then(res => {
      console.log(res.data.token);
      let token = res.data.token;
      console.log(token);

      // $.ajax()

      axios.post(
        'http://12.0.0.1:8000/api/',
        {
          headers: {
            'Content-Type' : 'application/json',
            'Accept' : 'application/json',
            'Authorization' : `JWT ${token}`
          },
        },
        {
          question_name: 'I am the the first question',
          user_id: '1',
          session_id: '1',
          data: {
            hello: ['armani', 'gucci'],
          },
          created: '2019-12-17T10:56:29.332637Z',
        },
      );
    })
    .catch(err => {
      alert('failed to login');
    });

在这段代码中,当我像这样粘贴该令牌时,我可以获得确切的令牌:

'Authorization' : `JWT <token>`

我的代码正在运行我不知道我尝试将其保存到本地存储使用时间间隔的问题是什么。在邮递员中,相同的查询工作正常。但在这里我没有取得任何成功。

【问题讨论】:

    标签: reactjs post axios


    【解决方案1】:

    让我知道 headers 对象内的这是否适合您:

    'Authorization' : `Bearer ${token}`
    

    【讨论】:

    • 试试这样Bearer JWT ${token}
    • 它不工作有什么办法可以记录标题
    • 转到 Chrome 开发工具,然后在网络选项卡中。所有 API 调用都将在此处列出。
    猜你喜欢
    • 2017-12-10
    • 2018-01-20
    • 2018-07-01
    • 2021-03-25
    • 2020-07-07
    • 1970-01-01
    • 2021-01-28
    • 2013-04-17
    • 2019-02-27
    相关资源
    最近更新 更多