SpringBoot如何配置CROS Filter
一、什么是CORS?
CORS是一個W3C標準,全稱是”跨域資源共享”(Cross-origin resource sharing),允許瀏覽器向跨源服務器,發(fā)出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
它通過服務器增加一個特殊的Header[Access-Control-Allow-Origin]來告訴客戶端跨域的限制,如果瀏覽器支持CORS、并且判斷Origin通過的話,就會允許XMLHttpRequest發(fā)起跨域請求。
CORS Header
- Access-Control-Allow-Origin: http://www.xxx.com
- Access-Control-Max-Age:86400
- Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
- Access-Control-Allow-Headers: content-type
- Access-Control-Allow-Credentials: true
含義解釋:

二、SpringBoot跨域請求處理方式
方式一
直接采用SpringBoot的注解@CrossOrigin(也支持SpringMVC)
Controller層在需要跨域的類或者方法上加上該注解即可
實戰(zhàn):

備注說明:Spring 版本必須大于等于4.2
方法二
處理跨域請求的Configuration
增加一個配置類CrossOriginConfig.java。
繼承WebMvcConfigurerAdapter或者實現(xiàn)WebMvcConfigurer接口
實戰(zhàn):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* AJAX請求跨域
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods(ORIGINS)
.maxAge(3600);
}方法三
采用過濾器(filter)的方式(推薦)
增加一個CORSFilter 類,并實現(xiàn)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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
*
* @ClassName: CorsFilter
* @Description: SpringBoot 跨域處理攔截器
*/
@Component
public class CROSFilter implements Filter {
public static final Logger logger = LoggerFactory.getLogger(CROSFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest reqs = (HttpServletRequest) req;
/*
* 跨域設置允所有請求跨域
* 如果允許指定的客戶端跨域設置: http://127.0.0.1:8020
*/
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}解決遇到的錯誤
1、Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
解決辦法
response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 2、Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
解決辦法:
if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring?Boot?Shiro?auto-configure工作流程詳解
這篇文章主要為大家介紹了Spring?Boot?Shiro?auto-configure工作流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
SpringBoot整合mybatis-plus進階詳細教程
本文主要對mybatis-plus的條件構造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動填充等知識點進行講解,需要的朋友參考下吧2021-09-09

