项目记录:跨域问题解决方案

2023-12-13 15:54:58

前端首页查询所有功能代码:

    queryAll()  {
      fetch("http://localhost:8096/schedule/all",
          {
                method: 'GET',
                credentials: 'include'
              })
          .then((response)  =>  {
            if  (response.ok)  {
              return  response.json();
            }
            else  {
              return  Promise.reject(new  Error("Failed  to  fetch  data"));
            }
          })
          .then((data)  =>  {
            this.scheduleData  =  data;  //  将返回的数据赋值给scheduleData
            this.searchResult  =  data;
            console.log(data)
          })
          .catch((error)  =>  {
            console.error(error);
          });
    }

出现下列报错:

Access to fetch at 'http://localhost:8096/schedule/all' from origin 'http://localhost:5173' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

解决方案,在cors配置类加上以下代码,不要使用通配符:

 corsConfiguration.addAllowedOrigin("http://localhost:5173"); // 设置访问源地址
 corsConfiguration.addAllowedOrigin("http://localhost:5174"); // 设置访问源地址

因为登录界面也有跨域问题,所以5174也要加进去。

还有以下报错:

Access to fetch at 'http://localhost:8096/schedule/all' from origin 'http://localhost:5173' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

解决方案,在拦截器功能代码第一行加上以下代码:

response.setHeader("Access-Control-Allow-Credentials", "true");

做完上述步骤后,跨域问题是解决了,用火狐浏览器也能得到token值了。其他功能也可以采用类似方法解决跨域问题。

文章来源:https://blog.csdn.net/m0_64694079/article/details/134902962
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。