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