什么是跨域?
- 定义:浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制
为什么需要跨域?
这个问题的始作俑者,请点击浏览器的同源策略。
具体分析,请参考文章:https://segmentfault.com/a/1190000015597029
如何跨域?
解决方案参考:
- 解决方案一:JSONP
- 解决方案二:CORS
- 解决方案三:WebSocket
- 解决方案四:iframe
- 解决方案五:代理
示例:spring-boot开发web应用通过CORS跨域
跨域访问方,client端的js代码
$.ajax({
url: "http://localhost:8081/api/get",
type: "POST",
data: {
name: "测试"
},
success: function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});
服务提供方核心代码配置
方式一:注解式控制,粒度细,更灵活
关键代码展示
@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;
}
方式二:全局控制,简单省事
关键代码展示
package com.roncoo.education.util.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 全局设置
* @author wujing
*/
@Configuration
public class CustomCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 限制了路径和域名的访问
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
};
}
}
- 跨域成功和失败的效果展示
成功:
失败:
小结:
本文设计的跨域,是端口不一致下的跨域访问。其他类型的跨域同理可证
附:代码下载
https://github.com/bill4j/spring-boot-course/tree/develop/spring-boot-cors
参考文章:
http://www.ruanyifeng.com/blog/2016/04/cors.html
http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html
https://segmentfault.com/a/1190000015597029