一、Web 開發(fā)經(jīng)常會(huì)遇到跨域問(wèn)題,解決方案有:jsonp,iframe,CORS 等等 CORS 與 JSONP 相比
1溯祸、 JSONP 只能實(shí)現(xiàn) GET 請(qǐng)求,而 CORS 支持所有類型的 HTTP 請(qǐng)求羽嫡。
2本姥、 使用 CORS,開發(fā)者可以使用普通的 XMLHttpRequest 發(fā)起請(qǐng)求和獲得數(shù)據(jù),比起 JSONP 有更好的 錯(cuò)誤處理。
3杭棵、 JSONP 主要被老的瀏覽器支持,它們往往不支持 CORS,而絕大多數(shù)現(xiàn)代瀏覽器都已經(jīng)支持了 CORS
瀏覽器支持情況
Chrome 3+
Firefox 3.5+
Opera 12+
Safari 4+
Internet Explorer 8+
二婚惫、在 spring MVC 中可以配置全局的規(guī)則,也可以使用@CrossOrigin
注解進(jìn)行細(xì)粒度的配置。
全局配置:
@Configuration
public class CustomCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
} };
} }
或者是
/**
* 全局設(shè)置
*
* @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;
} }
測(cè)試 js:
$.ajax({
url: "http://localhost:8081/api/get",
type: "POST",
data: {
name: "測(cè)試" },
success: function(data, status, xhr) {
console.log(data);
alert(data.name);
} });
細(xì)粒度配置
/**
* @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;
} }