【问题标题】:How to pass JsonWebToken x-access-token through reactjs while using API?使用API​​时如何通过reactjs传递JsonWebToken x-access-token?
【发布时间】:2018-08-13 01:07:15
【问题描述】:

如何在使用带有 react 的 API 时传递动态 JWT x-access-token?我知道如何使用 fetch 方法使用 API。

componentDidMount(){
    fetch('http://example.com/api/admin/dailyPosts')
    .then(response => response.json())
    .then(response => {
      this.setState({
        postCount: response
      })
    })
  }

在安慰 this.state.postCount 时,我得到一个空数组,因为没有提供令牌。那么如何将动态令牌传递给这个 API?

【问题讨论】:

  • 你的服务器端是什么样子的?您使用的是 express 或 passport.js 之类的吗?
  • 这和 React 有什么关系?
  • 不,我没有使用快递或护照。我只是在处理 create-react-app 模块。

标签: reactjs api jwt


【解决方案1】:

当您从 API 获得或生成令牌时,将其设置为浏览器的 cookie,如

import { Cookies } from 'react-cookie';
Cookies.set(token, auth_token_here, {path: '/'});

设置从浏览器获取cookie并在请求方法中设置带有令牌的标头对象

import { Cookies } from 'react-cookie';

componentDidMount(){
    let auth_token = Cookies.get(token)
    let header_obj = {'Authorization': auth_token};
    fetch(url, { headers : header_obj}).then();
}

假设您将令牌存储在浏览器中或可作为来自 redux 的 props

【讨论】:

  • Akhilesh,谢谢你的回答。实际上,我不知道如何将令牌存储在存储中。如果你能帮忙,那就太好了。谢谢。
  • 我在我的项目 npmjs.com/package/react-cookie 中使用了 react-cookie。使用 react-cookie 编辑了答案。
猜你喜欢
  • 2016-08-21
  • 2019-04-23
  • 1970-01-01
  • 2021-11-22
  • 2020-04-17
  • 2021-04-07
  • 1970-01-01
  • 2019-07-11
  • 2021-07-26
相关资源
最近更新 更多