测试大概是这么写的

@RestController
public class UserController {
    @RequestMapping(\"/test\")
    public void login(HttpServletResponse response) {
            Cookie cookie = new Cookie(\"test\",\"test\");
            cookie.setMaxAge(30 * 60);//半小时过期
            cookie.setPath(\"/\");//(\"/\")表示的是访问当前工程下的所有webApp都会产生cookie
            cookie.setHttpOnly(false);
            response.addCookie(cookie);
    }
}

这个是配置类

@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(\"/**\")
                .allowedOrigins(\"*\")
                .allowedMethods(\"POST\", \"GET\")
                .maxAge(30*60)
                .allowCredentials(true);//设置成允许操作cookie
    }
}

如果现在直接浏览器访问地址,确实可以看到存入了cookie,但是我react的请求可以看到响应头部的set-cookie有值,但是浏览器的cookie中没有存入,后面的解决是设置了react的fetch请求中credentials:‘include’,参数,就可以存储到浏览器了,如果是其他的ajax也是相似的,也要设置credentials

收藏 打印