You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中使用fetch能否从响应结果中获取cookies?

如何在fetch API中获取响应返回的Cookies

fetch的实现在浏览器端和Node.js服务端有差异,对应获取、管理Cookie的方案也不一样,以下是两种场景的具体实现:

浏览器端场景

浏览器出于同源安全策略限制,对Cookie的读写有严格管控:

  • 如果你只需要实现类似requests.Session的会话保持能力,不需要手动读写Cookie,只需要为fetch配置credentials参数即可:
    • 同域请求设置credentials: 'same-origin'(默认值,大部分场景可以省略)
    • 跨域请求设置credentials: 'include'
      配置后浏览器会自动在请求中携带对应域的有效Cookie,也会自动存储响应返回的Cookie,行为和Python的requests会话完全一致。
  • 如果你确实需要在JS代码中读取Cookie:
    1. 首先确认目标Cookie没有设置HttpOnly标记,设置了该标记的Cookie完全不允许JS读取,只能由浏览器自动管理
    2. 同域下可直接通过document.cookie读取当前域下所有可访问的Cookie
    3. 如果需要读取响应头中的Set-Cookie字段,需要后端额外配置Access-Control-Expose-Headers: Set-Cookie,否则前端无法读取该响应头
      示例代码:
// 带凭证的fetch请求,自动处理Cookie存取
fetch('https://your-domain.com/api/endpoint', {
  credentials: 'include' // 跨域请求必须加这个配置
}).then(res => {
  // 后端配置了暴露Set-Cookie头时可以读取该字段
  const setCookieHeader = res.headers.get('Set-Cookie')
  console.log(setCookieHeader)
  // 同域下直接读取当前域可访问的所有Cookie
  console.log(document.cookie)
})

Node.js 服务端场景

Node.js环境下的fetch实现没有内置会话管理能力,你可以选择手动维护Cookie,或者使用封装好的第三方库实现类似requests.Session的能力:

方案1:手动维护Cookie容器

// 全局存储Cookie的容器
let cookieJar = ''
async function fetchWithSession(url, options = {}) {
  const response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Cookie: cookieJar
    }
  })
  // 存储响应返回的新Cookie
  const newCookies = response.headers.getSetCookie()
  if (newCookies.length) {
    cookieJar = newCookies.join('; ')
  }
  return response
}
// 使用方式
await fetchWithSession('https://your-domain.com/api/login')
// 后续请求自动携带之前存储的Cookie
const userRes = await fetchWithSession('https://your-domain.com/api/userinfo')

方案2:使用第三方封装库

可以搭配tough-cookie和fetch-cookie库快速实现完整的会话管理能力,不需要手动处理Cookie逻辑:

import fetch from 'node-fetch'
import { CookieJar } from 'tough-cookie'
import { FetchCookie } from 'fetch-cookie'
// 初始化Cookie容器和带会话的fetch实例
const cookieJar = new CookieJar()
const sessionFetch = new FetchCookie(fetch, cookieJar)
// 直接使用即可,自动处理Cookie的存取
await sessionFetch('https://your-domain.com/api/login')
const userInfo = await sessionFetch('https://your-domain.com/api/userinfo')
// 直接读取当前存储的所有Cookie
const cookies = await cookieJar.getCookies('https://your-domain.com')
console.log(cookies)

内容的提问来源于stack exchange,提问作者noobcode0000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:36:02