【Vue-Spring跨域Bug已解决】has been blocked by CORS policy: The value of the······

一.问题发现

报错内容:

p://localhost:8001/user/login’ from origin ‘http://localhost:3001’ 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’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

前后端分离项目:

前端:Vue3-Element-Admin

后端:SpringCloud

后端接口已写好,用postman检测正常。

在这里插入图片描述

但是在搭建好前端项目后,进行数据传输时报错:

image-20230412192355658

二.问题解决过程

一开始怀疑为前端策略问题。检查后也更改了后端接口的域名并且是放行的所有的请求。

proxy: {
    
    
'/api': {
    
    
target: '*', 
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, ''),
},
},

还是报错如下:

image-20230412192604376

2.1 询问AI结果

这个报错提示是因为在跨域请求中,请求头中设置了 withCredentials 参数为 true,表示跨域请求需要使用凭证(如 cookies、HTTP 认证等)。而在响应头中,Access-Control-Allow-Origin 的值不能是通配符 *,必须是具体的域名。

你可以尝试在后端服务器的响应头中设置 Access-Control-Allow-Origin 的值为前端应用的域名,比如:

Access-Control-Allow-Origin: http://localhost:3001

这样就可以解决这个报错问题了。

另外,如果你在发送跨域请求时需要携带 cookies 或其他凭证,还需要在请求头中设置 withCredentials 参数为 true。比如:

const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://example.com/api');
xhr.send();

或者使用 Fetch 发送请求时设置 credentials 参数为 ‘include’。比如:

fetch('http://example.com/api', {
    
    
  credentials: 'include'
});

但是这个回答并不能解决我的问题。

2.2 问题解决

后端Spring写了@CrossOrigin,依旧无法解决问题。

我发现前端的请求头中设置了 withCredentials 参数为 true。

后端也需要配置相应的

@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")

这里的允许域名可以写为允许全部。

@CrossOrigin(origins = “*”, allowCredentials = “true”)

如此再次请求,问题就已解决。

image-20230412194101417

三.知识点

使用 @CrossOrigin 注解可以完成后端服务器的响应头中设置 Access-Control-Allow-Credentials 的值为 true。在 Spring Boot 中,使用 @CrossOrigin 注解可以很方便地实现跨域支持,同时支持设置是否允许使用凭证。

例如,在 Spring Boot 中使用 @CrossOrigin 注解可以实现以下方式:

@RestController
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class MyController {
    
    
    @GetMapping("/my-api")
    public String myApi() {
    
    
        return "Hello World";
    }
}

在上述代码中,我们在 MyController 类上添加了 @CrossOrigin 注解,设置 origins 为前端应用的域名,同时将 allowCredentials 设置为 true,表示允许使用凭证。

需要注意的是,使用 @CrossOrigin 注解只适用于单个控制器或方法的跨域支持。如果需要全局配置跨域支持,应该使用上一条回答中提到的方式,在配置类中设置 CorsConfigurationSource

allowCredentials 是 CORS 中的一个选项,用于指示是否允许在跨域请求中发送和接收凭据。凭据可以是例如 Cookies、HTTP 认证信息(如使用 Basic、Digest 或 NTLM 方式进行身份验证)或 TLS 客户端证书等敏感信息。

如果将 allowCredentials 设置为 true,则客户端请求中包含的凭据将被发送到服务器,并且服务器响应中的 Access-Control-Allow-Credentials 头部将被设置为 true。这样,就可以在跨域请求中携带和接收敏感信息。

猜你喜欢

转载自blog.csdn.net/weixin_52908342/article/details/130115085