在发送了跨域的http请求的,在网络请求中可以看到set-cookie中是有值的,但是通过浏览器擦看cookie却发现并没有存储。

Pasted image 20250207230939

解决办法:

  • 前端

在构建ajax请求时,添加withCredentials

const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  withCredentials: true
})
  • 后端

配置跨域处理,其中若无.exposedHeaders("Authorization");则前端无法获取到请求头中的Authorization的值

@Configuration  
public class WebConfig implements WebMvcConfigurer {  
    @Override  
    public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**") // 允许跨域请求的所有路径  
                .allowedOrigins("http://localhost:8081") // 允许的源  
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法  
                .allowedHeaders("*") // 允许的请求头  
                .allowCredentials(true) // 是否允许发送Cookie  
                .exposedHeaders("Authorization"); // 指定暴露的响应头,必须指定字段,不能为*  
    }  
}