set-cookie无法存入到浏览器cookie问题汇总系列

Vue前端set-cookie 问题解决

1 修改axios默认配置, 使得每次请求默认携带cookie.  main.js全局配置的

import axios from 'axios'

axios.defaults.withCredentials=true;


后端Java set-cookie 问题解决

1 后端设置前端可以跨域的配置

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
class CrossConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://domain.com")
                //.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                //.allowedHeaders("Set-Cookie","Referer","Host","Origin","Accept","DNT",
                //        "X-Mx-ReqToken","Keep-Alive","User-Agent","X-Requested-With",
                //        "If-Modified-Since","Cache-Control","Content-Type","Authorization")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
                //.allowedHeaders("*");
    }
}

注意Origins必须为前端域名,不能为*号

2 设置 cookie 属性


@Bean("sessionIdCookie")
public SimpleCookie sessionIdCookie(){

    SimpleCookie simpleCookie = new SimpleCookie("sid");
    log.info(domain);
    simpleCookie.setDomain(domain.com);
    simpleCookie.setHttpOnly(true);
    simpleCookie.setSameSite(Cookie.SameSiteOptions.valueOf("NONE"));
    simpleCookie.setSecure(true);
    simpleCookie.setPath("/");
    //maxAge=-1表示浏览器关闭时失效此Cookie
    //simpleCookie.setMaxAge(-1);
    return simpleCookie;

这样就可以解决前后端模式下,后端不能设置cookie


Nginx 配置后端跨域(此方法最终证明还是有效的)

add_header 'Access-Control-Allow-Methods' 'GET,OPTIONS,PUT,POST,PATCH,DELETE' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Headers' Set-Cookie,Referer,Host,Origin,Accept,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;
if ($request_method = OPTIONS ) {
    return 200;
}