简体   繁体   English

使用API​​时如何通过reactjs传递JsonWebToken x-access-token?

[英]How to pass JsonWebToken x-access-token through reactjs while using API?

How do I pass dynamic JWT x-access-token while using an API with react? 在使用带有React的API时如何传递动态JWT x-access-token? I know how to use the API using fetch method. 我知道如何通过提取方法使用API​​。

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

While consoling this.state.postCount, I get an empty array as no token is provided. 安慰this.state.postCount时,我得到一个空数组,因为没有提供令牌。 So how do I pass the dynamic token to this API? 那么如何将动态令牌传递给此API?

When you have the token from API or generated, set it as cookie to the browser like 当您从API获得令牌或生成令牌后,将其设置为浏览器的Cookie,例如

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

Set get the cookie from the browser and set header object with the token in the request method like 设置从浏览器获取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();
}

Assuming you have the token stored in the browser or is available as props from redux 假设您已将令牌存储在浏览器中,或者可以从redux中用作道具

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 输入 '{ 'x-access-token': any; } | {'x-access-token'?:未定义; }' 不可分配给类型 'AxiosRequestHeaders | 不明确的' - Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequestHeaders | undefined' 我该如何解决:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 x-access-token? - How can I fix : Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response? 无法将 access_token 传递到 Reactjs 中的端点 - Unable to pass access_token to endpoint in Reactjs 在reactjs中使用API​​ 时如何将数据从一个组件传递到另一个组件 - How to pass data from one component to another while using API in reactjs Azure AD Token generaiton using reactjs, to access WebAPI and SharePoint REST API/GrapAPI using jwt token - Azure AD Token generaiton using reactjs, to access WebAPI and SharePoint REST API/GrapAPI using jwt token 如何使用reactjs通过window对象将应用程序变量传递到控制台? - How to pass a application variables through window object to console using reactjs? 如何传递我可以访问 API 的身份验证令牌?(反应问题) - How to pass auth token that I can access API?(react question) 如何将参数传递给 api?reactjs - how to pass parametrs to api?reactjs 如何使用 reactjs 中的 axios 通过 api 从数据库中获取数据? - how fetch data from database through api using axios in reactjs? REACTJS 使用 fetch 通过 const 传递变量 - REACTJS Pass variable through const using fetch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM