码迷,mamicode.com
首页 > 编程语言 > 详细

java 前后端跨域问题解决

时间:2019-05-29 14:53:00      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:文件   oid   except   pos   代码   res   methods   ESS   red   

 前端页面部署在nginx 上 ,后端代码部署在服务器上 ,前端访问后台会出现跨域问题

 

新建一个过滤器

/**
* 开放跨域权限
*
* */
@Slf4j
public class testFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException{

// System.out.println("执行过滤操作");

HttpServletResponse response = (HttpServletResponse) var2;

response.setHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Allow-Headers",
"User-Agent,Origin,Cache-Control,Content-type,Date,Server,withCredentials,AccessToken");

response.setHeader("Access-Control-Allow-Credentials", "true");

response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");

response.setHeader("Access-Control-Max-Age", "1209600");

response.setHeader("Access-Control-Expose-Headers", "accesstoken");

response.setHeader("Access-Control-Request-Headers", "accesstoken");

response.setHeader("Expires", "-1");

response.setHeader("Cache-Control", "no-cache");

response.setHeader("pragma", "no-cache");

var3.doFilter(var1, response);
};

public void destroy() {
}
}

在配置文件中配置filter


@Bean
public FilterRegistrationBean filterRegist() {
FilterRegistrationBean frBean = new FilterRegistrationBean();
frBean.setFilter(new testFilter());
frBean.addUrlPatterns("/*");


return frBean;
}


前端页面 ajax 中添加
xhrFields: {
withCredentials: true
},
属性

java 前后端跨域问题解决

标签:文件   oid   except   pos   代码   res   methods   ESS   red   

原文地址:https://www.cnblogs.com/liangb/p/10943409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!