11

I know that this is a newby question, but I am new to learning Ajax. I was reading some code and came across this line

xhrFields: {withCredentials: true}

I was able to follow the rest of the code; however, this part is a little confusion. Do you use it to be able to overwrite the credentials?

In the documentation it says the following:

xhrFields Blockquote

Type: PlainObject

An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

I kind of get what it is saying. However, I am unsure of what kind of cross-domain requests it is referring to.

I am sorry again for asking this noob question. Please do not downvote my question D:

Have a wonderful day :)!

Tom Oconnor
  • 393
  • 2
  • 5
  • 14
  • Or [mdn: XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) `[...]The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. [...]` – t.niese Aug 24 '18 at 19:21

1 Answers1

7

As per the Mozilla docs:

The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests

As per the CORS spec the cookies are not sent, but when you set the XMLHttpRequest.withCredentials = true the cookies will be sent to the server running in a different domain. Usually if the server API is located in a different domain the cookies are not sent.

This property when set for the same origin request has no effect. But in order for this to work, the server must also enable credentials by setting the Access-Control-Allow-Credentials response header to true.

Refer the Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • Can we send the cookie to server (which is located in different domain) if we browse the client application in private or incognito mode? – Salman Aug 08 '20 at 14:26