前后端分离跨域问题汇总CORS

一、跨域通信的问题,即CORS。默认会403

1、现象:前端调用会报错“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource”,后端收不到请求。

2、方案,后端设置:Access-Control-Allow-Origin

2.1 springboot2的话,可以设置:

2.1.1 接口类或方法注解的方式

@CrossOrigin

2.1.2 拦截器的方式

package com.order.config;


import com.google.common.collect.Lists;
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 java.util.List;

/**
 * 实现基本的跨域请求
 */

@Configuration
public class GlobalCorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        List<String> allowedOriginList = Lists.newArrayList();
        allowedOriginList.add("http://localhost:3000");
        allowedOriginList.add("http://localadmain.com");
        corsConfiguration.setAllowedOrigins(allowedOriginList);
//        corsConfiguration.addAllowedOrigin(allowedOriginList); // 允许任何域名使用
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

二、登录状态保持的问题

处理了问题一,后面的ajax请求还会有401的问题,因为丢失了登录状态。方案有:

1、共享cookie的方式。

前端:

<script>
    $(function () {
        $.ajax({
            url : "http://www.b.com:8888/test/setCookie",
            method: "get",
            success : function (json) {
                console.log(json);
            },
            xhrFields: {
                withCredentials: true
            }
        });
    })
</script>

 后端:

@CrossOrigin(origins="http://www.a.com:8888",allowCredentials = "true")

CorsConfiguration corsConfiguration = new CorsConfiguration();
        List<String> allowedOriginList = Lists.newArrayList();
        allowedOriginList.add("http://localhost:3000");
        allowedOriginList.add("http://localadmain.com");
        corsConfiguration.setAllowedOrigins(allowedOriginList);
//        corsConfiguration.addAllowedOrigin(allowedOriginList); // 允许任何域名使用
        corsConfiguration.setAllowCredentials(true);

  

2、token的方式:

可以自己实现,也可以借助:

jwt

oauth2

z

相关推荐