Skip to content

Instantly share code, notes, and snippets.

@AlexVonB
Last active August 6, 2018 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexVonB/77e100c10b95ffc18e05b36bbe2d5d76 to your computer and use it in GitHub Desktop.
Save AlexVonB/77e100c10b95ffc18e05b36bbe2d5d76 to your computer and use it in GitHub Desktop.
How to set up CORS on your server and jQuery

CORS with Ajax Requests

Serverside

Server response has to have these headers:

Access-Control-Allow-Origin:      https://origin.com
Access-Control-Allow-Methods:     POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers:     Content-Type, X-Auth-Token, Origin
Access-Control-Allow-Credentials: true

where https://origin.com is the querying host. In case of sending login credentials: Origin must not be *; the browser would reject the server's answer.

Additionally catch OPTIONS-requests and respond with 200 OK and the headers if the requesting host is on the whitelist. 4XX else. Make sure that 4XX-responses send those headers, too.

Clientside

$.ajax({
  ...,
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  }
})

Cookies

Enable third party cookies in your browser. Cookies for localhost are not persistent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment