Jhipster默認對跨域的支持
但是要怎麼用,還是看你了....
什麼是跨域
瀏覽器的同源策略導致了跨域.
同源策略限制了從同一個源加載的文檔或腳本如何與來自另一個源的資源進行交互。這是一個用於隔離潛在惡意文件的重要安全機制。
爲什麼要跨域
簡單的一點說明就是,不同的服務器之間進行接口調用.
如何跨域
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)跨域資源共享 CORS 詳解。看名字就知道這是處理跨域問題的標準做法。CORS有兩種請求,簡單請求和非簡單請求。\
JHipster的跨域解決方案:
JHipster中給的配置文件爲:
jhipster:
http:
version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration)
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
使用注入bean的方式,來進行對url path的攔截
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
}
return new CorsFilter(source);
}
cors中對需要傳入的是path路徑...
這裏就是有個坑....
使用原生的JHipster的構建的框架中.register攔截的路徑是/api/**,即/api下所有的目錄及子目錄,而我們在寫接口的時候,接口名稱是不會添加/api,而是直接寫簡單的業務名稱來區分不同的接口名稱,這也就是說.我們註冊攔截的需要進行跨域的是/api/**下所有的接口,而我們寫的接口不在這個目錄下面,所以就會出現接口不滿足跨域的問題...
改爲/**後就是對所有的接口路徑進行攔截....
TIPS
/** 的意思是所有文件夾及裏面的子文件夾
/* 是所有文件夾,不含子文件夾(如果在某個請求下的子文件夾請求就不會攔截,很多ajax都不會被攔截)
/ 是web項目的根目錄
如果我們只需要對某個特定的接口名稱進行跨域操作,只需要更改path的這個匹配路徑即可....
如/api/cors/* 只允許有三層,且前兩層是/api/cors
/api/cors/** 至少有三層,且前兩層是/api/cors
如果是簡單的springmvc項目(springboot或者ssm等框架的)
1,可以通過直接注入cors的configuration來實現
package com.trs.idap.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by Administrator on 2019/2/12.
* 描述:
*
* @author Young
* @create 2019-02-12 15:58
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
.maxAge(3600);
}
}
2,可以在方法上或者類上直接添加註解
@CrossOrigin(origins = "*", maxAge = 3600)
實現跨域操作