首页 > 解决方案 > 使用不记名令牌的 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));
  });

标签: reactjstokenbearer-token

解决方案


我认为您必须在服务器中启用 CORS。


推荐阅读