Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

跨域或同域时cookie的设置 #1

Open
Yuanfang-fe opened this issue Jun 10, 2020 · 0 comments
Open

跨域或同域时cookie的设置 #1

Yuanfang-fe opened this issue Jun 10, 2020 · 0 comments
Labels

Comments

@Yuanfang-fe
Copy link
Owner

Yuanfang-fe commented Jun 10, 2020

使用cookie的目的:

因为HTTP是一个无状态的协议,所以在服务端接收请求时无法判断请求者的身份,而cookie可以用来作为判断用户身份的凭证。

同域

例如:
前端地址: https://a.demo.com/index.html
后端地址:https://a.demo.com/api/setCookie

如果在响应头出现了set-cookie,会将cookie的值保存在https://a.demo.com
image

跨域

例如:
前端地址: https://a.demo.com/index.html
后端地址:https://b.demo.com/api/setCookie
cookie会设置在 https://b.demo.com 下面

本地开发

例如:
前端地址: http://127.0.0.1:8000/
后端地址:http://127.0.0.1:3000/setCookie

如果后端服务是本地服务,那么无论是跨域还是同域都不能设置cookie

如果修改了hosts,也是无法传递cookie的
前端地址: http://test.cookie.com:8000/
后端地址:http://test.cookie.com:3000/setCookie
image
那本地开发怎么设置cookie呢?

一、调用远端的域名接口
例如:
前端地址: http://127.0.0.1:8000/
后端地址:http://google.com/api/demo

二、同源!!!(协议+ 域名+ 端口)

例如利用反向代理将http://127.0.0.1:8000/api 转发到http://127.0.0.1:3000/
例如:

 proxy: {
      // change http://127.0.0.1:8000/api/setCookie => http://127.0.0.1:3000/setCookie
      ['/api']: {
         target: `http://127.0.0.1:3000/`,
         pathRewrite: {
            ['^/api']: ''
         }
      }
    },

demo:
https://github.com/Yuanfang-fe/Blog-X/tree/master/demos/cookie

备注:
另外chrome升级80之后,set-cookie时 sameSite属性的默认值由 none 变成了 lax , 会导致某些场景cookie无法使用,详情点这里
image

参考:

mqyqingfeng/Blog#157

如果以上有不对的地方,请务必指正,十分感谢。

@Yuanfang-fe Yuanfang-fe changed the title cookie 跨域或同域时cookie的设置 Jun 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant