1. 程式人生 > >CORS 跨域請求實現

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 埠 的跨域請求就能成功,是不是很簡單。