We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
在写 koa 的时候,本地建了一个 index.html 想测试一下请求的情况 代码如下:
fetch('http://localhost:3000/')
发现由于同源策略要求,会产生跨域问题。 浏览器的同源策略的要求: 域名(或者ip)、协议、端口都要相同,不相同即为跨域 CORS 请求默认不发送 Cookie 和 HTTP 认证信息。如果要把 Cookie 发到服务器,必须得在服务端设置响应头、在客户端添加 XMLHttpRequest 的属性 withCredentials 为 true。
服务端,
设置 Access-Control-Allow-Credentials 为字符串小写的 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' })
app.use(cors({ origin: 指定的域名, credentials: true }));
app.use(async ctx => ctx.cookies.set(key: value))
fetch(url, { method: 'GET', credentials: 'include' })
完成之后发现 chrome 的控制台的 network 看不到 cookie !但其实抓包出来是有的。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
关于同源策略要求产生的跨域问题实践
在写 koa 的时候,本地建了一个 index.html 想测试一下请求的情况
代码如下:
发现由于同源策略要求,会产生跨域问题。
浏览器的同源策略的要求: 域名(或者ip)、协议、端口都要相同,不相同即为跨域
CORS 请求默认不发送 Cookie 和 HTTP 认证信息。如果要把 Cookie 发到服务器,必须得在服务端设置响应头、在客户端添加 XMLHttpRequest 的属性 withCredentials 为 true。
解决思路
服务端,
设置
Access-Control-Allow-Credentials
为字符串小写的true
。设置 Access-Control-Allow-Origin 该值不能为通配符* ,并且只能指定单一域名。
前端,
打开 withCredentials 属性,否则,即使服务器同意发送Cookie,浏览器也不会发送。例如
具体的解决办法
app.use(cors({ origin: 指定的域名, credentials: true }));
app.use(async ctx => ctx.cookies.set(key: value))
fetch(url, { method: 'GET', credentials: 'include' })
完成之后发现 chrome 的控制台的 network 看不到 cookie !但其实抓包出来是有的。
参考文章:
The text was updated successfully, but these errors were encountered: