Fetch API 获取 response cookie、模拟登录获取 cookie
在尝试 Fetch API 模拟登录时,碰到一个很纳闷的事。就是明明浏览器的 Response Headers 中可以看到 set-cookie 字段。但却无法获取。

尽管我最终运行环境是在 Nodejs 下使用 node-fetch 运行的。但为了调试方便,我还是习惯先在浏览器控制台中使用 fetch 调试一下。
这就是最大的坑!
浏览器的 Fetch API 由于安全策略,是无法获取 Response Headers 的 set-cookie 字段的。
但是,在 Nodejs 环境下使用 node-fetch 是可以正常获取的。
const fetch = require('node-fetch')
fetch("https://ikuuu.co/auth/login", {
"headers": {
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
},
"body": "email=521573740%40qq.com&passwd=123456&code=&remember_me=on",
"method": "POST",
"mode": "cors",
"credentials": 'include'
}).then(res => {
// 获取 cookie
const cookie = res.headers.get('set-cookie')
// 清理一下 cookie 的格式,移除过期时间,只保留基础的键值对才能正常使用
const real_cookie = cookie
.replace(/expires=(.+?);\s/gi, '')
.replace(/path=\/(,?)(\s?)/gi, '')
.trim()
// 带着 cookie 发起请求
fetch('https://ikuuu.co/user/checkin', {
method: 'POST',
// 加入 cookie
headers: { cookie: real_cookie, },
// 必须配置这个才可以携带 cookie
credentials: 'include',
}).then(res => res.json()).then(data => {
console.log(data)
})
})
如果我想在浏览器的 Fetch API 中获取 cookie 怎么做?
其实既然是在浏览器中使用调试。那直接调用 document.cookie 获取即可。尽管这样做毫无意义。
fetch("https://ikuuu.co/auth/login", {
"headers": {
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
},
"body": "email=521573740%40qq.com&passwd=123456&code=&remember_me=on",
"method": "POST",
"mode": "cors",
"credentials": "include"
}).then(res => {
console.log(document.cookie)
})

浙公网安备 33010602011771号