---
title: "前后端分离，spring boot跨域问题"
author: "ninghq"
date: "2018-09-23T23:15:56Z"
tags: []
categories: ["编程语言"]
slug: "spring-boot"
draft: false
lastmod: "2018-09-23T23:17:51Z"
id: 2431245
url: "https://ninghq.iteye.com/blog/2431245"
---

**跨域：浏览器同源策略**

1995年，同源政策由 Netscape 公司引入浏览器。目前，所有浏览器都实行这个政策。

最初，它的含义是指，A网页设置的 Cookie，B网页不能打开，除非这两个网页"同源"。所谓"同源"指的是"三个相同"

协议相同/域名相同/端口相同

一句话：浏览器从一个域名的网页去请求另一个域名的资源时，域名、端口、协议任一不同，都是跨域

浏览器控制台跨域提示：

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

**解决方法**

1）JSONP

2）Http响应头配置允许跨域（通过cors协议解决跨域问题）

 

Cors协议:H5中的新特性：Cross-Origin Resource Sharing（跨域资源共享）。通过它，我们的开发者（主要指后端开发者）可以决定资源是否能被跨域访问。

cors是一个w3c标准，它允许浏览器（目前ie8以下还不能被支持）像我们不同源的服务器发出xmlHttpRequest请求，我们可以继续使用ajax进行请求访问。

具体关于cors协议的文章 ，可以参考http://www.ruanyifeng.com/blog/2016/04/cors.html 这篇文章

第一步：nginx层配置（可以参考https://www.cnblogs.com/hawk-whu/p/6725699.html）

```
server{
listen 8099;
server_name wdm.test.cn;
location / {
　　// 没有配置OPTIONS的话，浏览器如果是自动识别协议(http or https)，那么浏览器的自动OPTIONS请求会返回不能跨域
　　if ($request_method = OPTIONS ) {
　　　　add_header Access-Control-Allow-Origin "$http_origin";
　　　　add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
　　　　add_header Access-Control-Max-Age "3600";
　　　　add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
　　　　add_header Access-Control-Allow-Credentials "true";
　　　　add_header Content-Length 0;
　　　　add_header Content-Type text/plain;
　　　　return 200;
　　}
　　add_header 'Access-Control-Allow-Origin' '$http_origin';
　　add_header 'Access-Control-Allow-Credentials' 'true';
　　add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';
　　add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
　　proxy_pass http://127.0.0.1:8080;
　　}
}
```

  第二步：程序代码中处理

SpringBoot自带配置

```
@Configuration
public class Cors extends WebMvcConfigurerAdapter {
@Override
 public void addCorsMappings(CorsRegistry registry) {
	 registry.addMapping("/**")
		 .allowedOrigins("*")
		 .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
		 .allowCredentials(true).maxAge(3600);
	}

}
```

 如果想做到更细致也可以使用@CrossOrigin这个注解在controller类中使用。

```
@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
@RequestMapping("rest_index")
@RestController
public class IndexController{}
```

 （注意点:假如接口报错，则跨域配置不生效）