我已经公开了Spring REST的API,并试图从独立的jquery代码POST数据。这是一个跨域请求。Spring REST&CORS支持不够好
我的配置如下
春 - 3.2.5.RELEASE,jQuery的 - 1.10.2
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Content-Type","application/json");
request.setRequestHeader("Authorization", basic);
request.setRequestHeader("Access-Control-Allow-Origin","*");
},
url: "http://localhost:8080/workflow/workflow-api/human",
data: '{"id":"1","firstName":"Tito","lastName":"LastName"}',
crossDomain:true,
processData: false,
success: function(msg) {
console.log("Login result:"+msg);
}
});
在Chrome开发者控制台,我得到下面的错误
XMLHttpRequest cannot load http://localhost:8080/stockingworkflow/workflow-api/human. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.
在web.xml中,CORS过滤条目如下
<filter>
<filter-name>cors</filter-name>
<filter-class>com.workflow.security.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我的过滤器类,如下
@Component
public class CorsFilter extends OncePerRequestFilter {
private static Logger logger = Logger.getLogger(AuthenticationService.class);
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
logger.debug("<-----Inside CORS filter---->");
if (request.getMethod().equals("OPTIONS")) {
logger.debug("<-----Inside OPTIONS---->");
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "x-requested-with");
response.addHeader("Access-Control-Max-Age", "1800");
}
filterChain.doFilter(request, response);
}
}
我调用由浏览器。HTML文件中打开HTML文件jQuery的Ajax请求由server.So在浏览器不提供我的网址是
文件:/// C:/Users/3467/Desktop/workflow/index.html
正如我已经启用了对C滤波器罗斯域的要求,理想的jQuery的Ajax请求应该有worked.But它说:
请求头字段访问控制允许来源不受 允许接入控制允许头
在我的开发者控制台下的“网络”,我看到OPTIONS GET请求是由浏览器发送的,它返回200 OK。意味着它碰到了CORS过滤器。下面是来自Chrome开发者工具的请求&响应头。
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/workflow/workflow-api/human
Request Method:OPTIONS
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,hi;q=0.6,id;q=0.4,ms;q=0.2
Access-Control-Request-Headers:access-control-allow-origin, accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:max-age=0
Connection:keep-alive
DNT:1
Host:localhost:8080
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.66 Safari/537.36
Response Headers
Access-Control-Allow-Headers:x-requested-with
Access-Control-Allow-Methods:GET, POST, PUT, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1800
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:0
Date:Mon, 22 Sep 2014 21:54:29 GMT
Server:Apache-Coyote/1.1
我不知道什么是错的,我有这么多跟随和Spring REST博客为CORS.Don't知道如果我失去了一些东西。