Reputation:
I have the Javascript function below. Whenever I run it (calling it from an Android app using WebView), it is sent as an application/x-www-form-urlencoded
despite having the dataType: "json"
attribute.
If I add contentType: "application/json; charset=utf-8"
then the request is not even received from the server and I get error:
XMLHttpRequest cannot load https://example.com/api. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
The request headers look like this:
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
The server is a Java Servlet running on Jetty Embedded that does not even have a WEB-INF or web.xml as it is not a web app but an API. The server does not even receive the request, so I guess it won't be solved by adding response.addHeader("Access-Control-Allow-Origin", "*");
Response header:
HTTP/1.1 200 OK
Allow: POST, TRACE, OPTIONS
Content-Length: 0
Server: Jetty(9.0.z-SNAPSHOT)
Client 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); });
}
EDIT: Tried doing this request without JQuery and still doesn't work.
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));
Upvotes: 0
Views: 1333
Reputation: 2121
This works for me (I'm using Tomcat
, not Jetty
though). I didn't do anything with the JSON
payload, just tested if the URL on the server is hit.
AJAX (plain 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 callback (the result)
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt2").innerHTML = this.responseText; //the result (success)
}
};
Upvotes: 0