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

React+TypeScript中js-cookie的Cookies.get()返回undefined问题排查

问题分析与解决方案

1. Secure属性导致本地HTTP环境无法读取Cookie

你设置Cookie时开启了secure: true,该属性要求Cookie仅能在HTTPS协议下被访问。但本地开发通常使用HTTP的localhost,这种场景下js-cookie无法读取到这个Cookie。

解决方法:
根据环境动态设置secure属性,仅在生产环境开启:

const setToken = (authToken: string) => {
  Cookies.set("authToken", authToken, {
    expires: new Date(Date.now() + 15 * 60 * 1000),
    secure: process.env.NODE_ENV === "production",
  });
};

2. Axios实例初始化时机过早,token未动态更新

你的服务代码在模块加载阶段就执行了Cookies.get("authToken")并创建axios实例,此时若用户是后续完成登录的,这个token变量不会自动更新,始终保持初始的undefined值。

解决方法:
改用axios请求拦截器,每次发起请求时再获取最新的token:

import axios from 'axios'
import Cookies from "js-cookie";
import { ProductTypes } from '../domain/entities/Product';
import { addProductResponse, getProductResponse } from '../domain/responses/productResponse';

const instance = axios.create({
  baseURL: 'http://localhost:8000/',
  headers: {
    "Content-type": "application/json",
  },
});

// 添加请求拦截器,每次请求前注入最新token
instance.interceptors.request.use((config) => {
  const token = Cookies.get("authToken");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export const addProduct = async(formValues:ProductTypes):Promise<addProductResponse>=>{
  return await instance.post(`/products/create-product`,formValues).then(
    (response:addProductResponse) => response
  )
}

3. 跨域场景下Cookie的Domain属性缺失

如果前端运行在localhost:3000、后端在localhost:8000(跨端口属于跨域),需要设置Cookie的domain属性为localhost,确保前端能正常读取:

const setToken = (authToken: string) => {
  Cookies.set("authToken", authToken, {
    expires: new Date(Date.now() + 15 * 60 * 1000),
    secure: process.env.NODE_ENV === "production",
    domain: "localhost",
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:51:01