解决springBoot出现 No 'Access-Control-Allow-Origin'

关于跨域问题 就不多介绍了!

针对跨域问题的解决方式(这里就简单说一下第一种):

  • CORS (Cross-Origin Resource Sharing)跨来源资源共享
  • JSONP
  • 代理请求方式

CORS请求原理

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

基本上目前所有的浏览器都实现了CORS标准,其实目前几乎所有的浏览器ajax请求都是基于CORS机制的,只不过可能平时前端开发人员并不关心而已(所以说其实现在CORS解决方案主要是考虑后台该如何实现的问题)。

CORS 对比 JSONP

都能解决 Ajax直接请求普通文件存在跨域无权限访问的问题

  1. JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求
  2. 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理
  3. JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS

这里使用CORS最简单的一种

@Bean
	public FilterRegistrationBean<Filter> registFilter() {
		FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<Filter>();
		registration.setFilter(new Filter() {

			public void init(FilterConfig filterConfig) throws ServletException {
				log.info("过滤器init!");
			}

			public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
				
				allowCrossAccess((HttpServletRequest)request, (HttpServletResponse)response);
				
				// 判断是否是预请求 OPTIONS  是则放行
				if((boolean) ((HttpServletRequest) request).getMethod().equals("OPTIONS")){
		        	System.out.println(((HttpServletRequest) request).getMethod());
		        	((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
		        	return;
		        }
				chain.doFilter(request, response);
			}

			public void destroy() {
				// TODO Auto-generated method stub
				log.info("过滤器destroy!");
			}
		});
		return registration;
	}


	protected void allowCrossAccess(HttpServletRequest request,HttpServletResponse response) {

		String allowOrigin = "*";
//		String allowOrigin = request.getHeader("Origin");
		String allowMethods = "GET,PUT,OPTIONS,POST,DELETE";
		String allowHeaders = "authorization,Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Cache-Control, Expires, Content-Type, X-E4M-With";

		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.addHeader("Access-Control-Allow-Headers", allowHeaders);
		response.addHeader("Access-Control-Allow-Methods", allowMethods);
		response.addHeader("Access-Control-Allow-Origin", allowOrigin);
		response.addHeader("Access-Control-Max-Age", "1800");//30 min
	}

 

二:Nginx 配置支持Ajax跨域

这里是一个nginx启用COSR的参考配置:来源

#
# Wide-open CORS config for nginx
#
location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
}

三:支持多域名配置的CORS Filter

因为知道已经有可以用的库可以解决,所以就没重复造轮子了。其实因为懒,看看别人的源码算了。。。

mvnrepository搜索cors-filter,目前也就两个可以用

这两个也都大同小异,因为ebay开源在github上,也有详细的README,那么就以ebay的cors-filter为例

配置

添加依赖包到项目:

<dependency>
    <groupId>org.ebaysf.web</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.0.1</version>
</dependency>

添加配置(具体配置项,还是见项目的README.md吧)

  <filter>
    <filter-name>CORS Filter</filter-name>
    <filter-class>org.ebaysf.web.cors.CORSFilter</filter-class>
    <init-param>
      <param-name>cors.allowed.origins</param-name>
      <param-value>http://192.168.56.129,http://192.168.56.130</param-value>
    </init-param>
    <init-param>
      <param-name>cors.allowed.methods</param-name>
      <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
      <param-name>cors.allowed.headers</param-name>
      <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CORS Filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 后面的第二、第三 转自 http://www.cnblogs.com/sloong/p/cors.html

本文发布后,无意看到一篇文章,这里贴一下整理的相关跨域问题,比较详细(推荐)

https://segmentfault.com/a/1190000012469713?utm_source=tag-newest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值