首页 > 解决方案 > 如何在reactjs中将令牌添加到标头

问题描述

我有一个想要使用的网络应用程序api。我想获取需要令牌的数据。我已经有了令牌 Ii 通过在我的邮递员中运行登录功能获得了令牌)。问题是:我把这个令牌放在哪里?有人说我需要把它放进去,headers但我找不到在哪里做这个headers。这是我的代码:

componentDidMount() {
  fetch('API_GOES_HERE', {
    headers: { Authentication: `Bearer ajsbdjabsjhdbfquhjwbeasbdasdjwbqjbds
  }})
 .then(res => res.json())
 .then(json => {
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
}

没有令牌,api 总是返回 this {"message":"missing or malformed jwt"}。我已经尝试从邮递员本身获取此数据并且它有效,因为我已经使用我的令牌设置了令牌变量。

ENDPOINT_API我通过将端点和令牌更改为and来审查端点和令牌API_TOKEN。谢谢,任何帮助将不胜感激。

标签: reactjsapi

解决方案


您需要在请求标头中包含令牌

fetch('API_ENDPOINT', {
   headers: { Authentication: `Bearer ${token}`
})
.then(res => res.json())
.then(json => {
    this.setState({
      contact: json,
      isLoaded: true,
    })
})
.catch(err => console.log(err));

推荐阅读