天天看点

前后端跨域cookie无法保存问题1.关于跨域问题2.我的问题及解决

1.关于跨域问题

跨域问题:域名,端口,子域不一样皆为跨域。

2.我的问题及解决

我遇到的问题是我的前端是3000接口,后端是8080接口,后端保存的cookie前端有接受,但是无法保存。

翻越了大量资料,首先需要配置后端的跨域。如果是前后端分离的项目,即使不玩cookie,依然需要设置。

后端设置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author : Jenson.Liu
 * @date : 2020/2/3  7:47 下午
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true); //允许接受cookie
        corsConfiguration.setMaxAge(1000L);
        corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

           

对于设置cookie的接口

@ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletResponse response,HttpServletRequest request, @RequestBody HashMap<String,String> map) {
        logger.info("username:"+map.get("username"));
        String token = TokenTool.createToken("username");
        Cookie cookie=new Cookie("token",token);
        cookie.setDomain(request.getServerName());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(60*60*24);
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
        return TokenTool.createToken("username");
    }
           

这里tooken就可以设置到前端域里面。

前端设置

前端设置非常简单,允许发送cookie即可

Axios.post('http://localhost:8080/dataService/login',
            this.state
            ,{            withCredentials: true}
            )
            .then(function (response) {
                console.log(response.data);
            })
            .catch(function (error) {
                console.log(error);
            });
           

通过这个接口,后端就获取了,前端请求发过来的cookie。前端请求也能查到token在前端域已经存在

Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("token")){
                    logger.info("token:"+cookie.getValue());
                    return cookie.getValue();
                }
            }
        }
           
前后端跨域cookie无法保存问题1.关于跨域问题2.我的问题及解决