Original address: github.com/yinxin630/b… Technical exchange: fiora.suisuijiang.com/
This article will answer the following questions:
- Can I set or read cookies for subdomains?
- What is the difference between setting cookies on the client and on the server?
- Do same-domain/cross-domain Ajax requests come with cookies?
Can I set or read cookies for subdomains?
No way! Cookies can only be set to the current field or higher
For example, client.com cannot set cookies to A.client.com, while A.Client.com can set cookies to client.com
Cookie reading is the same as above
What is the difference between setting cookies on the client and on the server?
For example, client.com cannot set cookies to server.com, and server.com cannot set cookies to client.com
The server can set httpOnly: true, and cookie clients with this property cannot read it
The client will only bring the cookie in the same domain as the request, for example, client.com/index.html will bring the cookie of client.com, server.com/app.js will bring the cookie of server.com, It also carries an httpOnly cookie
However, if it is an Ajax request to the server, cookies are not included, as detailed in question 3
Do same-domain/cross-domain Ajax requests come with cookies?
The problem has to do with how you make ajax requests
By default, fetch does not carry cookies for either same-domain or cross-domain Ajax requests. Only when the credentials are set, the cookies of the domain in which the Ajax requests reside are carried. The access-Control-allow-credentials header needs to be set to true on the server. Otherwise, the browser reports an error due to security restrictions and cannot obtain the response
Axios and jQuery take cookies with them in same-domain Ajax requests, but not in cross-domain requests, which require the withCredentials and server-side response headers to be set
Set the fetch credentials
By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.
Make the fetch take a cookie
fetch(url, {
credentials: "include".// include, same-origin, omit
})
Copy the code
- Include: Cross-domain Ajax with cookies
- Same-origin: only same-domain Ajax with cookies
- Omit: Do not omit cookies under any circumstances
Developer.mozilla.org/en-US/docs/…
Axios set withCredentials
//
withCredentials
indicates whether or not cross-site Access-Control requests, should be made using credentials // default: withCredentials: false
Make Axios wear a cookie
axios.get('http://server.com', {withCredentials: true})
Copy the code
Github.com/axios/axios…
JQuery set withCredentials
$.ajax({
method: 'get'.url: 'http://server.com'.xhrFields: {
withCredentials: true}})Copy the code
Yq.aliyun.com/articles/61…