reactjs - 使用不记名令牌的 React API 调用已被 CORS 策略阻止
问题描述
我正在尝试使用不记名令牌进行 API 调用以获取数据。但是 CORS 策略已阻止从源“http://localhost:3000”获取“https://MYAPI..”的错误访问:对预检请求的响应未通过访问控制检查:没有“访问” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。另外,我的令牌是空的。我尝试从 localStorage 获取。本地存储令牌示例这是我的令牌。任何人都可以向我建议我的问题在哪里?谢谢
const [user, setUsers] = React.useState([]);
var token = localStorage.getItem("accessToken");
React.useEffect(()=>{
fetch(URLS.GetAllUsers,{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
}})
.then(res=> res.json())
.then((response) => {
setUsers(response.displayName)
})
.catch((error) => console.log(error));
});
解决方案
我认为您必须在服务器中启用 CORS。
推荐阅读
- c - OpenGL 1.4。当我使用鼠标拾取更改旋转中心时,场景会发生变化
- javascript - 如何添加新节点
验证 - magento2 - 如何将输入值保存到数据库 magento2
- c - 如何通过将节点传递给另一个函数来分配内存?
- sqoop - 使用 sqoop 从 Mysql 中提取值到 HDFS
- javascript - 如何检查 DOM 节点文本值数组是否等于某个字符串?
- windows - git svn clone 卡在 perl.exe
- php - 带有 Bootstrap 网格的 Wordpress 循环。如何优化这段代码?
- flutter - Flutter 如何计算屏幕宽度
- android - 无法获取资源“https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom”