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

关于同源策略要求产生的跨域问题实践 #12

Open
wuzhenquan opened this issue Sep 30, 2018 · 0 comments
Open

关于同源策略要求产生的跨域问题实践 #12

wuzhenquan opened this issue Sep 30, 2018 · 0 comments
Labels

Comments

@wuzhenquan
Copy link
Owner

wuzhenquan commented Sep 30, 2018

关于同源策略要求产生的跨域问题实践

在写 koa 的时候,本地建了一个 index.html 想测试一下请求的情况
代码如下:

fetch('http://localhost:3000/')

发现由于同源策略要求,会产生跨域问题。
浏览器的同源策略的要求: 域名(或者ip)、协议、端口都要相同,不相同即为跨域
CORS 请求默认不发送 Cookie 和 HTTP 认证信息。如果要把 Cookie 发到服务器,必须得在服务端设置响应头、在客户端添加 XMLHttpRequest 的属性 withCredentials 为 true。

解决思路

  • 服务端,

    • 设置 Access-Control-Allow-Credentials 为字符串小写的 true

      // koajs,设置响应头 Access-Control-Allow-Credentials: true 
      res.header("Access-Control-Allow-Credentials", true);
    • 设置 Access-Control-Allow-Origin 该值不能为通配符* ,并且只能指定单一域名。

      // koajs,设置响应头 Access-Control-Allow-Credentials: true 
      res.header("Access-Control-Allow-Origin", "http://119.29.102.27");
  • 前端,

    • 打开 withCredentials 属性,否则,即使服务器同意发送Cookie,浏览器也不会发送。例如

      fetch('http://localhost:3000/users', {
      	method: 'GET',
      	credentials: 'include'
      })

具体的解决办法

  • 服务端
    • koa 用这个 https://github.com/koajs/cors (当然自己加也是很简单的事情)。
    • 代码:app.use(cors({ origin: 指定的域名, credentials: true }));
    • 代码:app.use(async ctx => ctx.cookies.set(key: value))
  • 前端
    • fetch(url, { method: 'GET', credentials: 'include' })

完成之后发现 chrome 的控制台的 network 看不到 cookie !但其实抓包出来是有的。

参考文章:

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