背景
- 前端Jquery+ajax
- 后端Springboot集成shiro
问题
前端调用ajax请求后端的api接口,出现Cors Error
解决方案
原理
配置针对跨域的过滤器,允许跨域请求,增加必要的跨域请求参数
来源
这是我看到一个博主给出的配置文件,实验了很多,就这个生效了。
package com.zt.common.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "shiroFilter")
@Slf4j
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 允许哪些Origin发起跨域请求
//String orgin = request.getHeader("Origin");
// response.setHeader( "Access-Control-Allow-Origin", config.getInitParameter( "AccessControlAllowOrigin" ) );
response.setHeader( "Access-Control-Allow-Origin", "*" );
// 允许请求的方法
response.setHeader( "Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT" );
//多少秒内,不需要再发送预检验请求,可以缓存该结果
response.setHeader( "Access-Control-Max-Age", "3600" );
// 表明它允许跨域请求包含xxx头
response.setHeader( "Access-Control-Allow-Headers", "*" );
//允许暴露给客户端的响应头
response.setHeader("Access-Control-Expose-Headers","token");
//prefight请求
if (request.getMethod().equals( "OPTIONS" )) {
response.setStatus( 200 );
return;
}
chain.doFilter( servletRequest, response );
}
@Override
public void destroy() {
}
}