[英]React API call with bearer token has been blocked by CORS policy
[英]React API call with bearer token
我是编码和反应的新手。 我正在尝试调用 API 来获取数据。 问题是给我的不记名令牌每 24 小时过期一次,我不知道如何在我的请求中将令牌代码作为变量插入到我的 header 授权中,以使其在需要时更新并交付给我 JSON信息。
像这样的东西可能会起作用
import React from 'react';
const App = () => {
const token = "yourtokenhere";
const [result, setResult] = React.useState();
React.useEffect(()=>{
fetch('https://example.test/', {
method: "POST",
headers: {"Authorization": `Bearer ${token}`}
}).then(res => res.json()).then(json => setResult(json));
},[]);
return (
<>
{JSON.stringify(result)}
</>
);
};
对于授权 header,我建议使用interceptor
。
拦截器可以在发出 API 请求和响应之前和之后执行诸如URL 操作、记录、将令牌添加到 header 等任务。
对于fetch() API 使用, npm install fetch-intercept --save
import fetchIntercept from 'fetch-intercept';
const registerIntercept = fetchIntercept.register({
request: function (url, config) {
// Modify the url or config here
const authHeader = new Headers(config.headers);
authHeader.append('Authorization', 'Bearer 232Qefsg4fg4g'); // your token
config.headers = authHeader;
return [url, config];
},
requestError: function (error) {
// Called when an error occured during another 'request' interceptor call
return Promise.reject(error);
},
response: function (response) {
// Modify or log the reponse object
console.log(response);
return response;
},
responseError: function (error) {
// Handle a fetch error
return Promise.reject(error);
}
});
对于Axios使用, npm install axios
axios.interceptors.request.use(req => {
// `req` is the Axios request config, so you can modify
// the `headers`.
req.headers.authorization = 'my secret token';
return req;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.