【发布时间】:2019-03-23 01:32:54
【问题描述】:
为了从 API 获取数据,我需要在调用的标头中发送一个 jwt 令牌。在我的应用程序中获取它后,我将它保存在本地存储中,当我在浏览器的控制台中检查时,我可以看到保存它有效 - 当我执行 localStorage.getItem('token' 时,我可以看到它出现在控制台中) 那里。但是当我尝试将它添加到我的 API 调用中时,我收到了 no jwt found 错误。显然,在执行从本地存储中获取令牌的逻辑之前,正在执行获取请求。下面是我的代码。任何有关如何解决此问题的建议将不胜感激。谢谢 !
const url = 'https://url.com';
const token = localStorage.getItem('token');
const AuthStr = 'Bearer '.concat(token);
export default class TestCall extends React.Component {
constructor(props) {
super(props);
this.state = {
error: undefined,
isLoaded: false,
items: [],
};
this.getData = this.getData.bind(this);
}
componentDidMount() {
this.getData();
}
getData () {
return fetch(url, {
method: 'GET',
headers:{
Accept: 'application/json',
'Content-Type': 'application/json',
},
Authorization: "Bearer " + AuthStr,
})
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<p>{items} </p>
);
}
}
}
更新:
根据我收到的答案,我将顶部的代码更改为:
const token = localStorage.getItem('token');
我删除了 const AuthStr。 所以我现在的获取请求是:
headers:{
Accept: 'application/json',
'Content-Type': 'application/json',
},
Authorization: "Bearer " + token,
})
这应该已经修正了错字,但我得到的响应仍然没有找到 jwt。
【问题讨论】:
标签: reactjs get authorization jwt fetch-api