天天看點

前後端跨域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.我的問題及解決