从javascript web服务客户端发送CORS POST请求返回http 405错误

Sending CORS POST request from javascript web-service client return http 405 error

本文关键字:请求 POST 返回 http 错误 CORS web javascript 服务 客户端      更新时间:2023-09-26

几天前,我实现了一个web服务(客户端"服务器)。客户端发送请求与XMLHttpRequest(),它是好的。然而,今天我试图改变发送请求从它到jquery的$.ajax();道路

下面是我的客户端函数:
function ajaxQuery(){
  $.ajax({
   url: 'http://localhost:8080/recommender/sider/drugs',
   method:'POST',
   dataType: 'json',
   contentType: 'application/json',
   data: JSON.stringify({"uris":["SampleName1", "SampleName2", "SampleName3"],"limit":100 }),
   xhrFields: {
      withCredentials: true
   }
}).done(function(data) { console.log(data) });
}

这是我在服务器端使用的过滤器

public class CORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws IOException, ServletException {
        if (response instanceof HttpServletResponse) {
            HttpServletResponse alteredResponse = ((HttpServletResponse) response);
            addCorsHeader((HttpServletRequest) request, alteredResponse);
        }
        filterChain.doFilter(request, response);
    }
    private void addCorsHeader(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Requested-By");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Max-Age", "1728000");
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

不幸的是,当我发送这个POST请求时,我得到了http 405错误,这是我错误部分的屏幕截图。https://www.dropbox.com/s/3wqlqkbnqwnjllx/screenshot%202015 - 08 - 18%——2011.27.29.png?dl=0

我该怎么处理这个问题?

您实际上是在发送GET请求,而不是POST。在$.ajax中使用了method。我怀疑您的jQuery版本低于1.9.0,应该使用type

$.ajax({
   ...
   type:'POST',
   ...

根据文档(http://api.jquery.com/jquery.ajax/):

)

method的别名。如果你使用的是1.9.0之前的jQuery版本,你应该使用type

我认为你需要改变数据类型为jsonp

{dataType: 'jsonp'}