我有下面的Javascript功能。每当我运行它(使用WebView从Android应用程序调用它)时,尽管具有application/x-www-form-urlencoded
属性,它仍以dataType: "json"
发送。
如果我添加contentType: "application/json; charset=utf-8"
,那么甚至没有从服务器收到请求,我收到错误:
XMLHttpRequest无法加载https://example.com/api。回应 预检请求未通过访问控制检查:否 '访问控制允许来源'标题出现在请求的上 资源。起源' null'因此不允许访问。
请求标头如下所示:
OPTIONS /api HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es;q=0.6
服务器是在Jetty Embedded上运行的Java Servlet,它甚至没有WEB-INF或web.xml,因为它不是Web应用程序而是API。服务器甚至没有收到请求,所以我想通过添加response.addHeader("Access-Control-Allow-Origin", "*");
回复标题:
HTTP/1.1 200 OK
Allow: POST, TRACE, OPTIONS
Content-Length: 0
Server: Jetty(9.0.z-SNAPSHOT)
客户端Javascript
function create(userId, callback) {
var submitData = {
"action": "create",
"userId": userId
};
$.ajax({
data: JSON.stringify(submitData),
type: "POST",
url: "https://www.example.com/api",
dataType: "json"
})
.done(function(data) { callback(SUCCESS); })
.fail(function() { callback(UNKNOWN_ERROR); });
}
编辑:尝试在没有JQuery的情况下执行此请求但仍然无法正常工作。
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "https://www.example.com/api");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.send(JSON.stringify(submitData));
答案 0 :(得分:1)
这对我有用(我使用的是Tomcat
,而不是Jetty
)。我没有对JSON
有效负载做任何事情,只是测试了服务器上的URL是否被命中。
AJAX(普通javascript)
function issueAjaxPost(){
var url = "http://localhost:8085/some_url/servlet/PostJson";
var json = '{ "action": "create", "userId": userId }';
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.send(json);
}
<强>的Servlet 强>
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String url = request.getRequestURL().toString();
String page = url.substring(url.lastIndexOf("/"));
...
if("/PostJson".equals(page)){
response.setContentLength("success".length());
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write("success");
}
}
AJAX回调(结果)
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt2").innerHTML = this.responseText; //the result (success)
}
};