Express.js如何将authCookie写入响应,使客户端浏览器可获取对应Cookie
解决方案
核心问题说明
你无法在自有服务的响应中为google.com域名写入Cookie,浏览器同源策略会直接拦截跨域名的Cookie设置操作,这是你之前Cookie始终为null的根本原因。同时你当前的CORS配置和fetch请求没有开启跨域凭证支持,就算是同域名下的Cookie也无法正常写入。
推荐方案:服务端代理资源(无Cookie跨域问题)
该方案不需要前端处理任何Cookie逻辑,由服务端完成谷歌网盘的授权校验后直接把资源流转发给前端,兼容性最好。
服务端代码修改
const express = require('express'); const htmlParser = require('node-html-parser'); const { parse } = htmlParser; const cors = require('cors'); const fetch = require('node-fetch'); const app = express(); const port = 8080; // 配置CORS允许跨域凭证 app.get('/video', cors({ origin: true, credentials: true }), async (req, ress) => { const response = await fetch('https://drive.google.com/uc?id=17OunL0rN-7jrsNGjznQTqnB_z7xfsgKK&export=download', { redirect: 'manual' }); const dom = parse(await response.text()); const url = 'https://drive.google.com' + dom.querySelector('#uc-download-link')._attrs.href; const resCookie = await response.headers.get('set-cookie').split(';'); const downloadCookie = resCookie[0]; const nidCookie = resCookie[6].split(',')[1]; const reqCookie = downloadCookie + ';' + nidCookie; let options = { headers: { cookie: reqCookie }, redirect: 'manual' }; const res = await fetch(url, options); const re = await fetch(await res.headers.get('location'), {redirect: 'manual'}); const authCookie = await re.headers.get('set-cookie').split(';')[0]; const r = await fetch(await re.headers.get('location'), { headers: { cookie: nidCookie }, redirect: 'manual' }); // 拿到最终资源地址后直接代理转发 const finalUrl = await r.headers.get('location'); const resourceRes = await fetch(finalUrl, { headers: { cookie: authCookie }, redirect: 'follow' }); // 透传资源响应头 ress.set('Content-Type', resourceRes.headers.get('content-type')); ress.set('Content-Length', resourceRes.headers.get('content-length')); // 把资源流返回给前端 resourceRes.body.pipe(ress); }); app.listen(port , () => { console.log(`Server is listening on ${port}`); });
前端代码修改
直接把视频地址指向你的服务接口即可,不需要额外请求直链:
<video id="video-player" controls src="http://127.0.0.1:8080/video"></video>
备用方案:同域名下Cookie写入方法(针对其他场景)
如果你是需要在自有域名下写入Cookie供自有服务使用,可按以下方式修改:
服务端写入Cookie
在返回响应前调用cookie方法:
// 写入authCookie ress.cookie('authCookie', authCookie, { httpOnly: false, secure: process.env.NODE_ENV === 'production', sameSite: 'Lax', maxAge: 24 * 60 * 60 * 1000 }); ress.send(await r.headers.get('location'));
前端fetch开启凭证支持
const response = await fetch('http://127.0.0.1:8080/video', { credentials: 'include' });
内容的提问来源于stack exchange,提问作者david stephen
相关产品推荐
相关产品推荐

