1.前端设置
前端其实在跨域上不需要进行任何设置,直接使用axios的官方示例即可
//axios.defaults.withCredentials =true;//让ajax携带cookie (这个必须要,否则无法跨域携带cookie)
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2.后端设置
cors跨域主要是需要在服务端进行配置
跨域设置
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties");
//允许访问的客户端域名
String origin = request.getHeader("Origin");
String[] allowDomainArr = props.getProperty("cors.allowed-origins").split(",");
List<String> allowDomain = Arrays.asList(allowDomainArr);
if (allowDomain.contains(origin)){
response.addHeader("Access-Control-Allow-Origin", origin);
}
//允许访问的方法名
response.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods"));
//允许服务端访问的客户端请求头,多个请求头用逗号分割,例如:Content-Type
response.addHeader("Access-Control-Allow-Headers", props.getProperty("cors.allowed-headers"));
//是否允许请求带有验证信息,若要获取客户端域下的cookie
response.addHeader("Access-Control-Allow-Credentials", props.getProperty("cors.allow-credentials"));
//预检验请求时间
response.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min
filterChain.doFilter(request, response);
}
配置设置
cors.allowed-origins=data-stg.ebc.jd.com
cors.allowed-methods=POST, GET, OPTIONS, DELETE
cors.allowed-headers=Content-Type,Cookie
cors.exposed-headers=
cors.allow-credentials=true
cors.max-age=1800