Thursday, September 21, 2017

$.get Cross Domain request with withCredentials: true


Even though $.get works for Cross-Domain(As long as CORS enabled), it doesn't send cross domain cookies while making request.

Meaning, let's say you have logged into https://cd-example.org and cookie is all set.
Now you want to make a cross domain request to https://cd-example.org from another domain https://example.org

If you make $.get("https://example-cd.org/someurl/",function(data){console.log(data)})
it won't work, because it doesn't send cd-example.org cookie. You need to use $.ajax with xhrFields: { withCredentials: true}

I just found a trick to workaround this $.get issue. Set {xhrFields: { withCredentials: true}} in $.ajaxSetup, which automatically gets attached to $.get and everything works magically.

So first
$.ajaxSetup({xhrFields: { withCredentials: true} })
and then make
$.get("https://example-cd.org/someurl/",function(data){console.log(data)})

No comments:

Post a Comment