background
The front-end and back-end separate projects, and the way the back-end returns cookies is as follows:
Configured on the frontend withCredentials = true
:
axios.defaults.withCredentials = true;
But the cookie information cannot be saved by the browser. Although the login interface returns 200, the login is actually invalid. At
this time, some information about the login interface:
reason
Articles online mention:
If you want to send cookies, Access-Control-Allow-Origin cannot be set to an asterisk, and you must specify a clear domain name that is consistent with the requested web page.
Looking at the screenshot of the response header above, I found that Access-Control-Allow-Origin has an address, which means that cookie information is allowed to be saved under this domain name. And
this address is obtained from the origin in the request header:
here host
, origin
and referer
What's the difference?
name | meaning |
---|---|
host | Indicates the destination of the current request to be sent. To put it bluntly, it is the host of the current request target resource, including only the domain name and port number. In any type of request, the request will contain this header information. |
origin | Indicates the protocol and domain name of the page where the currently requested resource is located. This parameter generally only exists in CORS cross-domain requests, and ordinary requests do not have this header |
refer | Indicates the full path of the page where the currently requested resource is located: protocol + domain name + query parameters (note that anchor information is not included, all types of requests include this header |
(The content of the table is taken from the difference between Host, Origin and Referer in the HTTP request )
When sending a request, the requested domain name is not localhost, so the cookie information cannot be saved by the browser. Therefore, a proxy needs to be configured to make the request url localhost.
configuration
Add proxy configuration in vue.config.js:
it means to /
represent the destination address, target
indicating the target address.
proxy: {
'/': {
target: 'http://47.115.203.105:38015/', // 代理地址,这里设置的地址会代替axios中设置的baseURL
changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
ws: true,
pathRewrite: {
'^/': ''
}
},
}
axios:
request information:
At this time, the cookie can be saved normally by the browser: