Spring Boot基礎教程11-web應用開發-CORS支持

 

 

一、Web開發經常會遇到跨域問題,解決方案有:jsonp,iframe,CORS等等

CORS與JSONP相比

1、JSONP只能實現GET請求,而CORS支持所有類型的HTTP請求。

2、使用CORS,開發者可以使用普通的XMLHttpRequest發起請求和獲得數據,比起JSONP有更好的錯誤處理。

3、JSONP主要被老的瀏覽器支持,它們往往不支持CORS,而絕大多數現代瀏覽器都已經支持了CORS

瀏覽器支持情況

Chrome 3+

Firefox 3.5+

Opera 12+

Safari 4+

Internet Explorer 8+

二、在spring MVC 中可以配置全局的規則,也可以使用@CrossOrigin註解進行細粒度的配置。

全局配置:

@Configuration

public class CustomCorsConfiguration {

@Bean

public WebMvcConfigurer corsConfigurer() {

return new WebMvcConfigurerAdapter() {

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");

}

};

}

}

或者是

/**

* 全局設置

* @author wujing

*/

@Configuration

public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {

 

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");

}

}

定義方法:

/**

* @author wujing

*/

@RestController

@RequestMapping("/api")

public class ApiController {

@RequestMapping(value = "/get")

public HashMap<String, Object> get(@RequestParam String name) {

HashMap<String, Object> map = new HashMap<String, Object>();

map.put("title", "hello world");

map.put("name", name);

return map;

}

}

測試js:

$.ajax({

url: "http://localhost:8081/api/get",

type: "POST",

data: {

name: "測試"

},

success: function(data, status, xhr) {

console.log(data);

alert(data.name);

}

});

細粒度配置

/**

* @author wujing

*/

@RestController

@RequestMapping(value = "/api", method = RequestMethod.POST)

public class ApiController {

 

@CrossOrigin(origins = "http://localhost:8080")

@RequestMapping(value = "/get")

public HashMap<String, Object> get(@RequestParam String name) {

HashMap<String, Object> map = new HashMap<String, Object>();

map.put("title", "hello world");

map.put("name", name);

return map;

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章