如何将每个React请求的身份验证令牌传递给后端API?

时间:2019-04-10 17:37:48

标签: reactjs

我有一个现有应用程序,其中已经开发了REST API。我正在考虑使用React JS开发前端,并且前端应在每次请求时调用我的REST API。

但是,当我登录到我的应用程序时,会生成一个令牌,该令牌作为身份验证标头传递给每个后续请求。我该如何使用React做到这一点? 我是React的初学者。

2 个答案:

答案 0 :(得分:0)

您可以将axios用作库,并将其添加为配置

axios.defaults.headers.common['Authorization'] = `Bearer ${token}` 

https://www.npmjs.com/package/axios

答案 1 :(得分:0)

使用fetch。示例:

var data = {myData: 'hello'}; // or just 'hello'

fetch(YOUR_URL, {
  method: 'POST', // or GET
  body: JSON.stringify(data), // data can be string or object
  headers:{
    'Authorization': YOUR_TOKEN,
    // ... add other header lines like: 'Content-Type': 'application/json'
  }
}).then(res => res.json()) // if response is json, for text use res.text()
.then(response => console.log('Response:', JSON.stringify(response))) // if text, no need for JSON.stringify
.catch(error => console.error('Error:', error));
相关问题