springboot webapi 支援跨域 CORS
阿新 • • 發佈:2018-12-16
1.建立corsConfig 配置檔案
@Configuration public class corsConfig { @Autowired varModel varModel_; @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override //重寫父類提供的跨域請求處理的介面 public void addCorsMappings(CorsRegistry registry) {//新增對映路徑 registry.addMapping("/**") .allowedHeaders("*") .allowedMethods("*") .allowedOrigins(varModel_.getCorsStrList()); } }; } }//end
2.varModel中的跨域設定
3.前端頁面ajax請求 頁面域名,http://localhost:8001
$.ajax({ type: "POST", url: "http://localhost:8000/a/b", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({ "requestId": "" }), success: function (d) { console.log(d); }, error: function () { //alert("系統錯誤"); } });
4.參考連結
跨域設定:
https://spring.io/guides/gs/rest-service-cors/
http://www.spring4all.com/article/177
https://www.jianshu.com/p/55643abe7a18
支援CORS跨域瀏覽器列表:
https://caniuse.com/#feat=cors