[英]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.