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

MERN全栈项目请求授权路由报Error: jwt malformed错误求助

问题原因

你遇到的问题核心是前端请求配置的生成时机错误:
你代码里的config对象是在JS模块初始化加载的时候就创建的,此时应用刚启动还未登录,getCookies('token')返回null,所以生成的请求头里Authorization的值固定为Bearer null。
你完成登录后虽然把有效token写入了cookie,但已经生成的config对象不会自动更新,后续发起需要授权的请求时还是携带的旧的无效token,就会触发jwt malformed错误。而刷新页面后所有JS模块会重新加载,此时config会重新生成,就能读取到cookie里最新的有效token,功能就恢复正常。

解决方案

推荐使用axios请求拦截器动态添加授权头,不要提前写死配置:

// 统一创建axios实例,配置通用参数
import axios from 'axios';
import { getCookies } from '../helpers/storage&cookies/storage&cookies';

const api = axios.create({
  baseURL: 'http://localhost:5020/api',
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器,每次请求前动态获取最新token
api.interceptors.request.use(
  (config) => {
    const token = getCookies('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 后续接口调用统一用这个实例,不需要单独传config了
export const signup = async (data) => {
  const response = await api.post('/auth/sign-up', data);
  return response;
};

export const postProduct = async (data) => {
  const response = await api.post('/products/create-product', data);
  return response;
}

如果不想用拦截器,也可以在每个需要授权的接口调用时,动态生成config对象,不要提前声明全局的config:

export const postProduct = async (data) => {
  // 请求时动态生成config,获取最新的token
  const config = {
    headers: {
      'Content-Type' : 'application/json',
      'Authorization' : 'Bearer ' + getCookies('token')
    }
  }
  const response = await axios.post('http://localhost:5020/api/products/create-product', data, config);
  return response;
}

额外校验点

可以顺便检查登录成功后写入cookie的逻辑,确保token写入时没有异步延迟的问题,不过按照你描述的刷新后就正常的现象,写入逻辑是正常的,不需要额外修改后端代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:30:04