如何在JavaScript的fetch请求中正确携带session cookie调用接口
解决方案
你之前尝试设置
Set-Cookie请求头的方案不符合HTTP规范:Set-Cookie是服务端响应头,用于通知浏览器存储Cookie,客户端发起请求时携带Cookie需要用到Cookie请求头,且浏览器环境默认禁止JS代码手动设置Cookie请求头,该字段由浏览器自动管理。
以下分两种运行场景给出实现方案:
场景1:代码运行在浏览器环境
前置条件
- 你的JS代码运行的页面域名和
https://fantasy.espn.com完全同源(协议、域名、端口三者一致) - 浏览器中已经在
fantasy.espn.com域名下存储了swid和espn_s2两个Cookie
实现代码
只要在fetch的第二个参数中添加credentials: 'include'配置,通知浏览器自动携带目标域名下的所有Cookie即可:
let leagueId = 1662510081; let endpoint = "mRoster"; let url = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/2021/segments/0/leagues/" + leagueId + "?view=" + endpoint; console.log(url); let playerList = []; fetch(url, { // 关键配置:通知浏览器携带对应域名的Cookie credentials: 'include' }) .then((response) => response.json()) .then((data) => { console.log(data) });
跨域场景额外说明
如果你的页面和ESPN域名不同源,除了加上述配置外,还需要ESPN服务端配置CORS规则允许你的域名访问,且开启Access-Control-Allow-Credentials: true,否则浏览器会拦截响应结果。
场景2:代码运行在Node.js环境
Node.js环境没有浏览器的请求头限制,可以直接手动设置Cookie请求头携带指定参数:
// 需提前安装node-fetch依赖:npm install node-fetch import fetch from 'node-fetch'; let leagueId = 1662510081; let endpoint = "mRoster"; let url = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/2021/segments/0/leagues/" + leagueId + "?view=" + endpoint; console.log(url); fetch(url, { headers: { // 手动拼接Cookie值,多个Cookie用分号+空格分隔 'Cookie': 'swid={A1cFeg47WrVdsREQZNAo}; espn_s2=AWDB51sqnG8dsc3wfdsffsd' } }) .then((response) => response.json()) .then((data) => { console.log(data) });
内容的提问来源于stack exchange,提问作者qwqwqwererer
相关产品推荐
相关产品推荐

