解決跨域請求的幾種方案
在前後端分離的項目中出現跨入問題。在此記錄下解決方式:
其實跨域問題的解決方式有多種,大致是:攔截器攔截請求、jsonp、第三方cor包、在spring MVC 4.2 中增加CORS支持非常簡單,可以配置全局的規則,也可以使用@CrossOrigin註解進行細粒度的配置、nginx反向代理。
爲什麼會出現跨域問題
這是一種安全策略,跨域:即只要協議名、域名、端口號中有一個不一樣,就會被判定爲是跨域請求。
解決方法
相關知識
- Access-Control-Allow-Origin:設置允許跨域的地址是什麼,請求頭中的Origin存的是調用方地址,*表示所有。
- Access-Control-Allow-Headers:有時調用方發送的請求中headers裏面會自定義頭信息,那麼被調用方也應該在響應中把headers返回回去,例如可以是這些值:Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Accept, Cache-Control, Expires, Content-Type, X-E4M-With,token,其中token是我自定義的。
- Access-Control-Allow-Methods: 允許跨域調用的方法是什麼類型,可以是:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH。
- Access-Control-Allow-Credentials:帶有Cookie的跨域請求,如果要利用session或cookie標識身份,此值必須設置爲true。
- Access-Control-Max-Age:非簡單請求,只要第一次通過OPTIONS檢查 在多久之內不會在調用OPTIONS進行檢測,單位秒。
1.攔截器(不建議使用)
創建filter類:
package cn.jiangdoc.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用攔截器攔截跨域請求
* @author jiangdoc
*
*/
public class SimpleCORSFilter implements Filter {
private boolean isCross = false;
@Override
public void destroy() {
isCross = false;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (isCross) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Max-Age", "0");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Accept, Cache-Control, Expires, Content-Type, X-E4M-With,token");
// 是否允許瀏覽器攜帶用戶身份信息(cookie)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
}
// 跨域的圖片上傳會用到
//OPTIONS 方法發起一個預檢請求,以檢測實際請求是否可以被服務器所接受。
if( "OPTIONS".equals(httpServletRequest.getMethod())){
System.out.println("圖片上傳");
//狀態碼(204),指示請求成功,但沒有要返回的新信息。
httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
}else{
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
}
}
在web.xml中配置:
<!-- 跨域配置-->
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>cn.jiangdoc.web.filter.SimpleCORSFilter</filter-class>
<init-param>
<param-name>IsCross</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- end -->
2.使用jsonp
前端代碼:
後端代碼:
每次都要對返回數據做處理比較繁瑣。
3.使用springmvc4.2或以上版本
- xml配置方式:
在spring-mvc.xml中添加配置:
<!-- springmvc4.1以上版本的接口跨域配置 -->
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
allow-credentials="true" />
</mvc:cors>
如果在bean解析的時候出錯:Cannot locate BeanDefinitionParser for element [cors]cvc-complex-type.2.4.c: 通配符的匹配無法找到元素 ‘mvc:cors’ 的聲明。
1.檢查springmvc的版本是不是4.2以上。
2.檢查springmvc.xml中的約束文件的版本。
下面是我的:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
</beans>
- 繼承WebMvcConfigurerAdapter
Java代碼:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
將該類注入到容器中:
<bean class="cn.jiangdoc.web.WebMvcConfigurerAdapter"></bean>
4.使用springmvc4.2或以上版本的@CrossOrigin註解
下面是源碼:
String[] DEFAULT_ORIGINS = { "*" };
String[] DEFAULT_ALLOWED_HEADERS = { "*" };
boolean DEFAULT_ALLOW_CREDENTIALS = true;
long DEFAULT_MAX_AGE = 1800;
可以看到該註解支持的類型和默認值。
使用方法只需要在controller層的類或方法上添加該註解並定義自己的想要的粒度。
例:
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
註解不起作用的原因:
1、是springMVC的版本要在4.2或以上版本才支持@CrossOrigin
2、非@CrossOrigin沒有解決跨域請求問題,而是不正確的請求導致無法得到預期的響應,導致瀏覽器端提示跨域問題。
3、在Controller註解上方添加@CrossOrigin註解後,仍然出現跨域問題,解決方案之一就是:在@RequestMapping註解中沒有指定Get、Post方式,具體指定後,問題解決。
推薦
5.nginx反向代理
在nginx的配置文件中:
server {
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
# add_header 'Access-Control-Max-Age' 3600;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
}