首先,我认为 Jersey 在这里做错了,因为 Content-Type 是一个描述请求/响应内容的标头,并且您没有在请求中包含任何内容,它实际上应该而是将其行为基于 Accepts 标头,但将其放在一边......
仅仅因为它是一个ajax调用,并不意味着content-type总是/,在客户端你可以像这样调用setRequestHeader:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myjaxrs-server/getSearchContacts");
xhr.onreadystatechange = function() {
/* normal javascript to deal with the response goes here */
};
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send("data i'm posting");
在 CORS 请求上设置 Content-Type 标头将导致预检发生。您必须支持服务器代码中的预检,否则 CORS 请求将被拒绝。为 getSearchContacts 提供您的正常代码,但预检将使用 OPTIONS 方法进行:
@OPTIONS
public Response preflight(
@HeaderParam("Access-Control-Request-Method") String requestMethod,
@HeaderParam("Origin") String origin,
@HeaderParam("Access-Control-Request-Headers") String requestHeaders) {
return Response
.ok()
.header("Access-Control-Allow-Origin", "*") // TODO replace with specific origin
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
现在将允许带有自定义标头的 CORS 请求。
这很容易出错:据我所知,即使是 google 电子表格 API 也无法正确响应预检,这意味着您实际上无法更改 javascript 中的任何数据。