Origin url is not allowed by Access-Control-Allow-Origin

ajax, cross-domain, jquery, spring-mvc

Solution

Since you're sending the request with content type `application/json` the client is forced to do a CORS pre-flight request.

The CORS specification says that any content type other than `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` requires a pre-flight request to determine whether the header is allowed.

Therefore, you'll need to handle the pre-flight request (HTTP method = `OPTIONS`).

To make it simple, let the server respond with the header:

Access-Control-Allow-Headers: *

That will allow all request headers.

UPDATE

I read your question again, and found something I don't understand: Why are you sending the `Content-Type` header in the first place for an HTTP GET request? This is not correct.

Just remove

headers: { 
   "Content-type" : "application/json"
}

and try again. That might fix it!

Problem

I know there are many questions already regarding this error. But, I'm still not able to get this working even after setting the header ``` "Access-Control-Allow-Origin" : "*" ``` on my server side. Here is my spring mvc controller method: ``` @RequestMapping(method=RequestMethod.GET, value="dummy/{num}") @ResponseBody public ResponseEntity<Result> dummy(@PathVariable String num) { int n = Integer.parseInt(num); final Result result = new Result(); result.setAddition(n+20); result.setMultiplication(n*20); result.setSubtraction(n-20); HttpHeaders headers = new HttpHeaders(); headers.add("Access-Control-Allow-Origin", "*"); ResponseEntity<Result> ent = new ResponseEntity<Result>(result,headers,HttpStatus.CREATED); return ent; } ``` And here is my AJAX call from Jquery ``` $.ajax({ url: "http://localhost:8010/Probe_Rest_Service/test/dummy/9", type: "get", crossDomain: true, dataType: 'json', headers: { "Content-type" : "application/json" }, success: function(data){ console.log("It worked!"); alert(data); }, error: function(){ // enable the inputs alert("error"); } }); ``` I tried calling my REST api from dev-http client for chrome and it works fine (the response header has Access-Control-Allow-Origin:* set) . But, when i call it from my html file, i get the error. I use JBoss for my rest api and tomcat for hosting my client webpage

Original source