您的位置:首页 > 编程语言 > Java开发

Spring Boot - Web 应用开发 - CORS

2018-03-17 00:48 786 查看
Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等

1. CORS 与 JSONP 比较

JSONP 只能实现 GET 请求,而 CORS 支持所有的 HTTP 请求。

使用 CORS,开发者可以使用普通的 XMLHttpRequest 发起请求和获得数据,比起 JSONP 有更好的错误处理。

JSONP 主要被老的浏览器支持,它们往往不支持 CORS,而绝大多数现代浏览器都已经支持了 CORS

2. 在 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://loclahost:8080");
super.addCorsMappings(registry);
}
};
}
}


或者是:

public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
}


定义方法:

c1a1
@RestController
@RequestMapping("/api")
public class ApiController {

@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}


测试 Ajax

$.ajax({
url: "http://localhost:8081/api/get",
type: "POST",
data: {
name: "测试"
},
success: function (data, status, xhr) {
console.log(data);
alert(data.name);
}
});


细粒度配置:

@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<>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: