Search code examples
javascriptpythonajaxcross-domaincors

CORS error on same domain?


I'm running into a weird CORS issue right now.

Here's the error message:

XMLHttpRequest cannot load http://localhost:8666/routeREST/select?q=[...] 
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin

Two servers:

  • localhost:8666/routeREST/ : this is a simple Python Bottle server.
  • localhost:8080/ : Python simpleHTTPserver where I run y Javascript application. This app is executing Ajax requests on the server above.

Any thought on what could be the problem?

EDIT:

And... the port was the problem. Thanks for your answers :)

If anyone is using a Python bottle server as well, you can follow the answer given on this post to solve the CORS issue: Bottle Py: Enabling CORS for jQuery AJAX requests


Solution

  • It is only the same if the scheme, domain and port are identical. Same Origin Policy

    Clarification

    • http and https are not the same scheme. (By default they also use different ports)
    • example.com and www.example.com are not the same domain.
    • Port 80 and 443 are not the same port.

    How to enable CORS

    If you want to enable CORS you must follow Cross-Origin Resource Sharing (cors) by adding headers. Mozilla has examples.

    In the incoming request you get an Origin header:

    Origin: https://example.com
    

    You need to add Access-Control-Allow-Origin as a header in your response. To allow everyone (you should probably NOT do that):

    Access-Control-Allow-Origin: *
    

    Multiple origins

    If you need to support multiple origins (for example, both example.com and www.example.com), set the Access-Control-Allow-Origin header in your response to match the Origin header in the request (provided you have verified that the origin is on the whitelist).

    WHY DO I GET REQUESTS WITH OPTIONS METHOD?

    Note that some requests send a preflight-request, with an OPTIONS-method, so if you write your own code you must handle those requests too. See Mozilla for examples.