spring+springmvc+mybatis项目在前后端联调时出现以下报错
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin’
说明出现了跨域问题。
可以有以下解决方法。
1.在controller类上加注解
@CrossOrigin(origins = "*", maxAge = 3600)
注:CrossOrigin是spring的注解
2.可以在web.xml添加过滤器
红框标注的class文件根据自己开发的实际位置填写。
类文件如下:
@Component
public class CORSFilteUtil extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
filterChain.doFilter(request, response);
}
}
跨域问题可以解决了。