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

如何在TanStack Query的useQuery中配置withCredentials: true

在TanStack Query useQuery中配置withCredentials获取Cookie

TanStack Query(原React Query)本身不直接处理请求配置,它只是执行你传入的请求函数,所以withCredentials的配置要写在你实际发起请求的工具(比如Axios或fetch)里,以下是两种常用场景的实现方式:

1. 继续使用Axios发起请求

直接在Axios的请求配置中添加withCredentials: true即可,useQuery会原样执行这个请求函数:

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

// 封装带withCredentials的请求函数
const fetchUserData = async () => {
  const res = await axios.get('/api/user/profile', {
    withCredentials: true // 关键配置
  });
  return res.data;
};

function UserProfile() {
  const { data: user } = useQuery({
    queryKey: ['userProfile'],
    queryFn: fetchUserData
  });

  // 组件渲染逻辑...
}

如果想给所有请求统一配置,可创建全局Axios实例:

// utils/axiosInstance.js
import axios from 'axios';

const axiosInstance = axios.create({
  withCredentials: true // 全局启用
});

export default axiosInstance;

之后在useQuery的请求函数里直接用这个实例:

import axiosInstance from './utils/axiosInstance';

const fetchUserData = async () => {
  const res = await axiosInstance.get('/api/user/profile');
  return res.data;
};

2. 使用原生Fetch发起请求

Fetch对应的配置是credentials: 'include',作用和Axios的withCredentials: true一致:

import { useQuery } from '@tanstack/react-query';

const fetchUserData = async () => {
  const res = await fetch('/api/user/profile', {
    credentials: 'include' // 关键配置
  });
  
  if (!res.ok) throw new Error('请求失败');
  return res.json();
};

function UserProfile() {
  const { data: user } = useQuery({
    queryKey: ['userProfile'],
    queryFn: fetchUserData
  });

  // 组件渲染逻辑...
}

注意事项

服务器端必须配合配置CORS头部:

  • 必须设置Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Origin不能设为*,要指定具体的前端域名(比如http://localhost:3000)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:35:35