CORS 跨域请求实现

什么是CORS?

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

什么是跨域?

跨域是指从一个域名的网页去请求另一个域名的资源。比如从www.baidu.com 页面去请求 www.google.com 的资源。跨域的严格一点的定义是:只要 协议,域名,端口有任何一个的不同,就被当作是跨域

下面是一个dva + springboot 实现的跨域请求处理,直接上代码:

(1)服务端实现

@Configuration
public class CORSConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins(
                                "http://127.0.0.1:6001",
                                "http://127.0.0.1:7001"
                        )
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}

(2)客户端实现:

if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`
    if (window.location.origin !== origin) {
      if (CORS && CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (YQL && YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }

我们来看一下CORS的定义:

CORS: [
		'http://127.0.0.1:6001',
		'http://127.0.0.1:7001',
	],

只要是由 127.0.0.1 : 6001 端口 访问 7001 端口 的跨域请求就能成功,是不是很简单。

猜你喜欢

转载自blog.csdn.net/diu_brother/article/details/79966579