一、简介
Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等
1.1、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+
二、实现CORS
说明:在springMVC中可以配置全局的规则,也可以使用@CrossOrigin注解进行细粒度的配置
2.1、全局配置
方式一:注册bean
package com.example.demo.utils.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;
/**
* Created by DELL on 2017/6/18.
*/
@Configuration
public class CustomCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
};
}
}
说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问
方式二:继承WebMvcConfigurerAdapter
package com.example.demo.utils.configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 跨域请求处理
* @Author: 我爱大金子
* @Description: 跨域请求处理
* @Date: Created in 10:12 2017/6/18
*/
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
}
说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问
2.2、细粒度配置
在controller中加入@CrossOrigin注解,如:@CrossOrigin(origins = "http://localhost:8080")
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。