java 前后端跨域问题解决
Posted liangb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 前后端跨域问题解决相关的知识,希望对你有一定的参考价值。
前端页面部署在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 前后端跨域问题解决的主要内容,如果未能解决你的问题,请参考以下文章