出现Access to XMLHttpRequest atNo AccessControlAllowOrigin header is present on the requeste

时间:2024-10-07 15:15:15

这里只讲常用的一种(jsonp只能处理get请求),首先要明白,为什么会发生这个错误,举个例子,在一个项目localhost:8888/a中利用ajax调用了localhost:9999/b中的请求,就发生跨域请求。

1. 如果用了Spring框架的话,那就简单了,因为Spring框架已经给我们封装好了,只需要在被请求的项目Controller中添加标记就可以
//解决ajax跨域问题
//@CrossOrigin(origins = "*",methods = {,})

  • 1
  • 2
  • 3
2.写一个Filter然后在修改请求的Origin和Methods,其中Origin中是代表放行那些请求,如localhost:8888/a那就表示这个请求可以,其他的都不可以Methods这个是请求的方式。记得
@WebFilter(filterName = "coursefilter",servletNames = {"dispatcherServlet"})
public class CourseFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httResponse = (HttpServletResponse) response;
        //允许访问的域名
        httResponse.setHeader("Access-Control-Allow-Origin","*");
        //允许提交的方式
        httResponse.setHeader("Access-Control-Allow-Methods","get,post,put,delete");
        chain.doFilter(request, response);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
3.这玩意简单…搜索一下ajax跨域问题,你会得到更详细的说明。