在前后端分離的項(xiàng)目中,以往跨域一般采用JSONP的方式派继,但是JSONP只支持GET請求宾袜,所以現(xiàn)在一般都不會采用JSONP的方式來處理跨域了。現(xiàn)在基本都是使用CORS的方式驾窟,要么在nginx中配置庆猫,如
add_header 'Access-Control-Allow-Origin' *;add_header 'Access-Control-Allow-Methods' *;
要么就在后臺服務(wù)器中配置response.setHeader("Access-Control-Allow-Origin", "*");......
以往只知道copy過來就Ok了,從未思考過這些參數(shù)的代表的意思绅络。直到最近在釘釘應(yīng)用的開發(fā)中踩到了坑阅悍,最終發(fā)現(xiàn)還是Access-Control-Allow-Headers配置為*導(dǎo)致不生效。所以對CORS做了較為深入的了解以及整理昨稼。
SpringBoot2.x版本關(guān)于CORS的配置
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
/**
* 跨域設(shè)置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("*")
.allowedHeaders("*");
}
}
SpringBoot1.x版本
@WebFilter(filterName = "corsFilter")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
參考
https://www.w3.org/TR/cors/
http://www.ruanyifeng.com/blog/2016/04/cors.html