39

Springboot CORS跨域访问

 4 years ago
source link: http://www.cnblogs.com/undefined22/p/12603553.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Springboot CORS跨域访问

什么是跨域

浏览器的同源策略限制: 它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

当一个请求url的 协议、域名、端口 三者之间任意一个与当前页面url不同即为跨域

举例:

当前页面url 被请求页面url ** 是否跨域** 原因 http://www.test.com/ http://www.test.com/index.html 否 同源(协议、域名、端口号相同) http://www.test.com/ https://www.test.com/index.html 跨域 协议不同(http/https) http://www.test.com/ http://www.baidu.com/ 跨域 主域名不同(test/baidu) http://www.test.com/ http://blog.test.com/ 跨域 子域名不同(www/blog) http://www.test.com:8080/ http://www.test.com:7001/ 跨域 端口号不同(8080/7001)

跨域的限制

【1】无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB

【2】无法接触非同源网页的 DOM

【3】无法向非同源地址发送 AJAX 请求

基于Springboot搭建CORS跨域访问

基于SpringBooot项目搭建可以站外Ajax请求访问的跨域资源服务器。

方法一:

在每个controller上添加 @CrossOrigin

其中@CrossOrigin中的2个参数:

origins: 允许可访问的域列表

maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。

未加@CrossOrigin:

@RestController
@RequestMapping("/test")
public class TestRequestLogController {

    @RequestMapping("/request_log")
    public String TestRequestLog(@RequestParam String name){
        return "hello " + name;
    }
}

fmEBZz2.jpg!web

加@CrossOrigin:

n2Qv6vZ.jpg!web

方法二:

@Configuration
public class CorsConfig {
    private CorsConfiguration corsConfiguration(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod(HttpMethod.GET);
        corsConfiguration.addAllowedMethod(HttpMethod.POST);
        corsConfiguration.addAllowedOrigin("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration());
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

aQjyimJ.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK