Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何将每个React请求的身份验证令牌传递给后端API?_Reactjs - Fatal编程技术网

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

Reactjs 如何将每个React请求的身份验证令牌传递给后端API?,reactjs,Reactjs,我有一个已经开发了RESTAPI的现有应用程序。我正在考虑使用React JS开发一个前端,前端应该在每个请求中调用我的REST API 但是,当我登录到我的应用程序时,会生成一个令牌,作为身份验证头传递给每个后续请求。如何使用React实现这一点? 我是React的初学者。您可以使用axios作为库,并将其添加为配置 axios.defaults.headers.common['Authorization'] = `Bearer ${token}` 您可以将axios用作库,并将其添加为配

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

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

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

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

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

axios.defaults.headers.common['Authorization'] = `Bearer ${token}` 
使用。例如:

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));
使用。例如:

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));

如何通过React代码与API通信?如何通过React代码与API通信?