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

React登录页面InvalidTokenError求助:登录成功却无法跳转

登录成功后未跳转,InvalidTokenError: Invalid token specified: must be a string

问题概述

后端返回200 HTTP响应(已验证登录成功),但页面未跳转至Home页。添加调试日志后触发以下错误:

Form submitted
Signin.jsx:35 Login successful {key: '53b53d027e69d35c0a03402c2f0b4bc0b932a50a'}
Signin.jsx:41 Login error InvalidTokenError: Invalid token specified: must be a string
    at jwtDecode (jwt-decode.js?v=699db677:38:11)
    at setTokenTimestamp (Utils.js:5:35)
    at handleSubmit (Signin.jsx:37:7)

问题根源

从日志可见,后端返回的登录成功数据仅包含key字段,而非setTokenTimestamp函数预期的refresh_token字段。当函数尝试解析data?.refresh_token时,该值为undefined,传入jwtDecode后触发非法token错误,导致代码进入catch块,navigate('/home')从未执行。

解决方案

1. 适配后端返回的token字段

修改utils.js中的setTokenTimestamp函数,使用后端实际返回的key字段,并添加空值与类型校验:

import {jwtDecode} from "jwt-decode";
export const setTokenTimestamp = (data) => {
    // 校验token合法性
    if (!data?.key || typeof data.key !== 'string') {
        console.error('Invalid token received');
        return;
    }
    try {
        const tokenTimestamp = jwtDecode(data.key).exp;
        localStorage.setItem("refreshTokenTimestamp", tokenTimestamp);
    } catch (err) {
        console.error('Failed to decode token:', err);
    }
};

2. 隔离token处理逻辑,避免阻断跳转

若跳转逻辑无需依赖token解析成功,可将token处理包裹在独立try-catch中,确保跳转不受影响:
修改SignIn.jsx的handleSubmit函数:

const handleSubmit = async (event) => {
    event.preventDefault();
    console.log('Form submitted');
    try {
        const { data } = await axios.post('/dj-rest-auth/login/', signInData);
        console.log('Login successful', data);
        setCurrentUser(data.user);
        
        // 独立处理token,失败不阻断主流程
        try {
            setTokenTimestamp(data);
        } catch (tokenErr) {
            console.error('Token processing error:', tokenErr);
        }
        
        console.log('Navigating to /home');
        navigate('/home');
    } catch (err) {
        console.log('Login error', err);
        setErrors(err.response?.data);
    }
};

额外检查点

  • 确认后端返回的key是否为JWT令牌:若不是JWT格式,需调整setTokenTimestamp逻辑(比如直接存储当前时间戳)。
  • 检查axios拦截器:确保没有拦截器修改响应数据结构,导致data字段不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:33:33