后台处理跨域问题

2021-09-01  本文已影响0人  Yluozi

CORS,全称是"跨域资源共享"(Cross-origin resource sharing)
它允许浏览器向跨源服务器发出XMLHttpRequest请求,从而克服了Ajax只能同源使用的限制。
基本思想是:使用自定义的HTTP头部允许服务器和浏览器相互了解对方,从而决定请求或响应成功与否。

本人了解的解决思路有三种:

1.使用@crossorigin注解,在Controller层加入:Handler阶段的CORS

2.CorsFilter: 过滤器阶段的CORS

3.CorsInterceptor: 拦截器阶段的CORS

过滤器CorsFilter 来配置跨域。

package net.cnki.knmarket.config;

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.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author ly
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }
    //改用过滤器CorsFilter 来配置跨域,由于Filter的位置是在Interceptor之前的,所以跨域冲突问题得到解决

    @Bean
    public CorsFilter corsFilter() {

        CorsConfiguration config = new CorsConfiguration();
        // 设置允许跨域请求的域名
        config.addAllowedOrigin("*");
        //config.addAllowedOrigin("http://192.168.107.43,http://192.168.107.43:5555,http://192.168.107.43:8800");
        // 是否允许证书 不再默认开启
        // config.setAllowCredentials(true);
        // 设置允许的方法
        config.addAllowedMethod("*");
        // 允许任何头
        config.addAllowedHeader("*");
        config.addExposedHeader("token");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

}

上一篇 下一篇

猜你喜欢

热点阅读