查看“︁编程语言/http/HEAD/Cookie 跨域”︁的源代码
来自康健生活
←
编程语言/http/HEAD/Cookie 跨域
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{sign}} ==引言== 如果验证登陆状态,大略有两种方法:cookie/session、token。(先假定后端网址:testapi.kangjian.xyz,前端网址:localnode.kangjian.xyz) 其中 token 的机制是通过 header 响应头设置诸如 x-token 的字段,eq: <syntaxhighlight lang="javascript" highlight="12"> Response Headers Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Content-Type,Content-Length, x-token Access-Control-Allow-Methods: PUT,POST,GET,DELETE,OPTIONS Access-Control-Allow-Origin: http://localnode.kangjian.xyz Content-Length: 11 Content-Type: application/json; charset=utf-8 Date: Wed, 12 Aug 2020 14:13:18 GMT ETag: W/"b-aRe3BK4Rb3jMT7oawHEhKRjcNhc" Server: nginx/1.18.0 X-Powered-By: 3.2.1 x-token: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjEwMDAxMjIsImNyZWF0ZWQiOjE1OTcxNDA2NTgzNTgsImV4cCI6MTU5NzIyNzA1OH0.mjqPORyFu_ZnojxqmhhH-d9EnFQ_UQj35SUAvh09P7exqY6nzk8NYHGnFIriOJZGAkxO3TtHevyJW67VJXnpeQ </syntaxhighlight> 客户端接收到请求头,然后提取 token 存放在 store (vue)中,每次与后端接口发送请求时再将 token 发送给后端进行校验并更新 token 返回。 如果是 cookie 机制,就需要后端在响应头中设置 set-cookie 字段,eq: <syntaxhighlight lang="javascript" highlight="11"> Response Headers Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Content-Type,Content-Length Access-Control-Allow-Methods: PUT,POST,GET,DELETE,OPTIONS Access-Control-Allow-Origin: http://localnode.kangjian.xyz Content-Length: 11 Content-Type: application/json; charset=utf-8 Date: Wed, 12 Aug 2020 14:13:18 GMT ETag: W/"b-aRe3BK4Rb3jMT7oawHEhKRjcNhc" Server: nginx/1.18.0 Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/ X-Powered-By: 3.2.1 </syntaxhighlight> 这里着重说 set-cookie,set-cookie 的参数细节参阅 [https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie HTTP/Headers/Set-Cookie],相关的文章网上众说纷纭却大同小异,不再赘述(其实水字数的人更多一点,很多都没有写到点子上)。 在后端设置 set-cookie 的时候一定要注意跨域问题,这个跨域涉及到两个层面,一是接口跨域,二是 cookie 跨域。 接口跨域使用 CORS 策略,将客户端浏览器上页面所在网址(即前端服务器网址)加入后端提供的响应头中: <syntaxhighlight lang="javascript" highlight="5"> app.use(express.static(path.join(__dirname, 'public'))); // 允许跨域 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localnode.kangjian.xyz"); // res.header("Access-Control-Allow-Origin", '*'); res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, x-token, x-cl , x-did, x-info, x-v, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8") if(req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/ else next(); }); app.use('/', indexRouter);</syntaxhighlight> 这样接口跨域跑通,之后是 cookie 跨域,找到文档规范 [https://tools.ietf.org/html/rfc6265#section-4.1 rfc6265] 中规定,cookie 跨域忽略端口,在设置 domain 为一级主域名之后(或 <code>www.一级域名</code>),子域名之间可以操控 cookie。 在后端代码设置简单的 set-cookie 方法,这里有一个很关键的 header 响应头字段是 <code>res.header("Access-Control-Allow-Credentials", "true");</code>。 {{hc|router/index.js|<syntaxhighlight lang="javascript"> router.get('/',function(req, res, next) { var result = {'dd':"cc"}; res.cookie("user",'kangkk',{ sameSite: false, domain:"kangjian.xyz" }) res.json(result); })</syntaxhighlight>}} 然后在前端页面请求后端接口时,一定要附带 <code>withCredentials = true</code>,我这里的项目是 nuxt,所以自带 @nuxt/axios。(这里有一个坑,我看了许多示例项目和网络帖子,发现很多人都是重新 npm install axios 而不是使用内置的 @nuxt/axios,这两者本质并没有区别,况且多加一个 axios 不冗余嘛,@nuxt/axios 已经完全够用了,axios 支持的 @nuxt/axios 也完全支持,不管是走 nuxt.config.js 里的 plugins 还是页面组件直接直连,都可以 hold 住。) 这里再简说一下我这边的 @nuxt/axios 设置,<code>plugins/axios.js</code> 组件扩展 @nuxt/axios,拦截请求头和响应头。这里着重说 <code>withCredentials = true</code>。在 @nuxt/axios 中已经内置参数 <code>credentials: true</code> (默认值 false),表示在请求中自动添加 <code>withCredentials = true</code>,<code>credentials: true</code> 需要在 nuxt.config.js 配置文件中的 <code>axios</code> 对象中设定,如果设定了这个值,那么所以从这里开始,不再需要添加 <code>withCredentials = true</code>,'''前提是 @nuxt/axios 的 baseURL 地址与接口地址一致'''。 以下,我展示调用接口的示例(自己写的架构,还有瑕疵): {{hc|pages/search/listLeft,vue|<syntaxhighlight lang="javascript"> import { TestSetCookie } from '@@/api/test' ... methods: { ... // 测试 coookie 跨域 new TestSetCookie(this.$axios) .fetch('GET') .then(value => { console.log(value) }) </syntaxhighlight>}} {{hc|api/test.js|<syntaxhighlight lang="javascript"> import { localTest } from '@/config/conf' export class TestSetCookie { constructor ($axios, context){ this.$axios = $axios; this.context = context; } async fetch (type) { const result = await this.$axios.call(null, { method: type || 'POST', url: localTest.textSetCookie, }) return result } }</syntaxhighlight>}} {{hc|config/conf.js|<syntaxhighlight lang="javascript"> let host = process.env.host // 开发环境客户端请求 api 代理 let proxyTable = host.proxyTable for (let key in proxyTable) { let targetHost = proxyTable[key].targetHost if (targetHost) { if (proxyTable[key].ifProxy && process.env.NODE_ENV === 'development') { host[targetHost] = key } else { host[targetHost] = proxyTable[key].target } } } ... /** * 自测模块 */ export const localTest = { textSetCookie: `${host.appLocalTestHost}/test`, // 后端测试接口 }</syntaxhighlight>}} {{hc|config/net.js|<syntaxhighlight lang="javascript"> export default { development:{ target:{ '/LOCAL': { targetHost: 'appLocalTestHost', target: 'http://testapi.kangjian.xyz', secure: false, changeOrigin: true, pathRewrite: { '^/LOCAL': '' }, ifProxy: false }, '/SEARCH': { targetHost: 'appSearchHost', target: 'http://localnode.kangjian.xyz/searchapi', secure: false, changeOrigin: true, pathRewrite: { '^/SEARCH': '' }, ifProxy: false }, '/APP': { targetHost: 'appHost', changeOrigin: true, target: 'http://local.kangjian.xyz:8086', pathRewrite: { '^/APP': '' }, ifProxy: false } }, staticHost: `/_nuxt/`, cloudStaticHost: `http://static.kangjian.xyz`, }, </syntaxhighlight>}} {{hc|config/env.js|<syntaxhighlight lang="javascript" highlight="43,44"> import netConfig from './net' /** * 由 npm 传值,如 npm run build --target=production,npm_config_target 为 production * @desc production、beta、gray、alpha、test * @type {string|string} */ export const target = process.env.npm_config_target || 'development' /* const prefix = target === 'production' ? '' : target const protocol = ~['production', 'beta', 'gray'].indexOf(target) ? 'https:' : 'http:' */ let map = { proxyTable: { }, staticHost: `` } Object.keys(netConfig).forEach(function (key){ if(key === target){ map.proxyTable = netConfig[key].target map.staticHost = netConfig[key].staticHost map.cloudStaticHost = netConfig[key].cloudStaticHost } }) export const host = map</syntaxhighlight>}} {{hc|plugins/axios.js|<syntaxhighlight lang="javascript"> import { Loading } from 'element-ui' import { stringify } from 'qs' import { getType } from './utils' import { whetherString } from './type' import { httpCode, httpStatus } from '@@/config/httpCode' export default ({ $axios, redirect, $cookies, router, store }) => { let ElementUiLoading = null let token = null if(process.server){ // 获取服务端的token } if(process.client){ // 获取客户端token token = $cookies.get('x-token'); } $axios.create({ timeout: 8000, }) // $axios.defaults.withCredentials = true // $axios.defaults.baseURL = 'http://testapi.kangjian.xyz' /** * request 拦截器 * @desc 将获取到 token 加入到请求头中 */ $axios.interceptors.request.use( (config) => { if(process.client){ /** * 页面加载状态 * @type {ElLoadingComponent} */ ElementUiLoading = Loading.service({ lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.3)', customClass:"osloading", fullscreen: true }) } // 动态设置baseurl config.baseURL = config.url.replace(/(http[s]{0,1}:\/\/[a-zA-Z0-9.-]+)?.*/i,'$1') config.headers['x-token'] = token; return config }, (error) => { ElementUiLoading.close() return Promise.reject(error) }); /** * response 拦截器 */ $axios.interceptors.response.use( (response) => { if(process.client){ ElementUiLoading.close() } console.log(response.headers) // if(response.status) httpStatus(response.status) const reqCode = (response && response.data && response.data.code) ?whetherString(response.data.code) ?response.data.code :(String(response.data.code)) :6000 return httpCode(reqCode).status?response.data.data:[] }, (error) => { if(process.client){ ElementUiLoading.close() } return Promise.reject({ code: '-100', message: `网络异常请稍后再试!${error}` }) }) } </syntaxhighlight>}} 这样设置就将 baseURL 动态设置为即将请求的接口的地址网址,然后 cookie 跨域成功。 在这里要实现三个统一、一个动态。即统一管理代理、统一管理接口、统一处理接口请求和返回值过滤,一个动态是指动态赋值 @nuxt/axios 的 baseURL 参数。 [[文件:Header setcookie eq jiekou 1.png|none|700px|左|Header setcookie eq jiekou 1]] 在实际项目中设置 set-cookie 有一些容易忽略的细节。 比如有很多人说 chrome 浏览器的 set-cookie 的 samesite 字段和 secure 字段,如果设置了 samesite=none,则必须同时设置 secure,然后接口走 https:443,才可以,eq: <pre> Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/; samesite=none; secure </pre> 但是这里有一个问题是 express 框架的 res.cookie方法遵循 [https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1 draft-ietf-httpbis-cookie-same-site-00] 规范,只有 <code>Strict</code> 和 <code>Lax</code> 值,没有 <code>none</code>。所以想要设置 <code>samesit=none</code>,要在 nginx 服务上进行代理 <syntaxhighlight lang="javascript"> location / { ... proxy_cookie_path / "/; httponly; secure; SameSite=none"; }</syntaxhighlight> 生成的响应头中 set-cookie 变更为 {{leftrightflex|<syntaxhighlight lang="javascript"> Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/;</syntaxhighlight> |<syntaxhighlight lang="javascript"> Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/; httponly; secure; SameSite=none</syntaxhighlight> }} 同时这一行字段抛错:this set-cookie was blocked because it had the secure attribute but was not received over a secure connection.(没有使用 https) 并且 cookie 并没有写入 application。所以在后端设置 samesite 为 false 最合适(在不使用 https 的情况下)。 两外需要注意的地方是 mock.js 与 xhr.js 的区别,如果使用了 mock.js (mock.js 没有注释掉),则需要改 mock.js (并非 mock 源码,而是 mock 的应用逻辑文件) <syntaxhighlight lang="javascript"> import Mock from 'mockjs' Mock.XHR.prototype.withCredentials = true Mock.mock(/\/demo\/test/,{ ... })</syntaxhighlight> ==其他== 浏览器(谷歌浏览器)在地址栏输入 [chrome://flags/ chrome://flags/],选择 <code>SameSite by default cookies</code> 和 <code>Cookies without SameSite must be secure</code> 选项
此页面嵌入的页面:
模板:Double-columns
(
查看源代码
)
模板:Double-columns/style.css
(
查看源代码
)
模板:Hc
(
查看源代码
)
模板:Hc/style.css
(
查看源代码
)
模板:Sign
(
查看源代码
)
模块:UrlDecode
(
查看源代码
)
返回
编程语言/http/HEAD/Cookie 跨域
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。