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

Qwik客户端发送会话Cookie,NestJS服务端未接收,原因何在?

问题分析

核心原因是Qwik的routeLoader$在服务器端执行,你当前使用的全局fetch是Node.js环境的请求,并非用户浏览器发起的请求,所以不会携带用户浏览器中的connect.sid Cookie。服务端日志里的user-agent: node也佐证了这一点——这个请求来自Qwik的服务器,而非客户端浏览器。

解决方案

方案1:使用Qwik的requestEvent.fetch(推荐)

Qwik的requestEvent提供了内置的fetch方法,会自动转发客户端的请求头(包括Cookie)到目标服务端,无需手动配置credentials。修改Qwik端代码如下:

export const useMe = routeLoader$(async (requestEvent) => {
    console.log(requestEvent.cookie.get('connect.sid'))
    console.log("Fetching the data.")

    // 替换全局 fetch 为 requestEvent.fetch
    const response = await requestEvent.fetch("http://localhost:3000/me");

    const data = await response.json();
    console.log(data)
    return data
})

方案2:将请求移至客户端执行

如果不需要在SSR阶段获取数据,可以把请求放到客户端生命周期钩子中(比如useVisibleTask$),确保请求从浏览器发起:

import { useVisibleTask$ } from '@builder.io/qwik';

export const useMe = component$(() => {
  useVisibleTask$(async () => {
    const response = await fetch("http://localhost:3000/me", {
      credentials: 'include',
    });
    const data = await response.json();
    console.log(data);
  });

  return <div>...</div>;
});
额外配置检查
  1. NestJS CORS 明确指定Origin
    避免CORS配置模糊导致的问题,明确填写Qwik应用的运行地址:

    const app = await NestFactory.create(AppModule, { 
      cors: {
        credentials: true,
        origin: "http://localhost:5173" // 替换为你的Qwik实际端口
      } 
    });
    
  2. 恢复Cookie的httpOnly: true
    之前为了调试设置httpOnly: false,现在可以改回true提升安全性——你不需要在客户端JS中直接操作connect.sid,httpOnly Cookie不会被JS访问,但依然会在请求中自动携带。

内容的提问来源于stack exchange,提问作者J.P. Irie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:21:02