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

求助:调用res.json()时出现‘res.json() is not a function’错误

解决res.json() is not a function登录请求错误

问题场景

发起fetch登录请求后,尝试通过const data = res.json()转换响应为JSON时,触发res.json() is not a function错误,无法正常获取用户数据用于全局页面使用。

客户端代码

const handleLogin = async (e) =>{
      e.preventDefault();
      try{
        dispatch(signInStart());
        const res = fetch(`${URL}/api/user/login`,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(user),
        });
        
        const data = await res.json();
        if(data.success === false){
            dispatch(signInFailure(data.message));
            return;
        }
        dispatch(signInSuccess(data));
        navigate('/upload');
      } catch(error){
        dispatch(signInFailure(error.message));
      }
  } ;

服务端代码

export const login = async(req,res,next) => {
    const { email, password } = req.body;
    try {
        const validUser = await User.findOne({email});  
        if(!validUser) return next(errorHandler(404,"User not found!"));
        const validPassword = bcryptjs.compareSync(password,validUser.password);
        if(!validPassword) return next(errorHandler(401,"Wrong credentials!"));

        const token = jwt.sign({id: validUser._id},process.env.JWT_SECRET);
        const { password: pass, ...rest} = validUser._doc;  // Excluding password from the user data we are getting
        res.cookie('access_token',token,{httpOnly: true, expires:new Date(Date.now() + 25892000000)})
        .status(200).json(rest)  //Expires after 30 days

    }catch(error) {
        next(error);
    }
};

错误原因

fetch是异步函数,调用后返回的是Promise对象,而非直接的Response实例。你没有在fetch前添加await,导致res变量存储的是Promise,而Promise没有json()方法,因此触发报错。

修复方案

在fetch调用前添加await,等待Promise解析为Response实例后再调用json()方法,同时调整错误判断逻辑(服务端返回的响应无success字段):

const handleLogin = async (e) =>{
      e.preventDefault();
      try{
        dispatch(signInStart());
        // 添加await获取实际的Response对象
        const res = await fetch(`${URL}/api/user/login`,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(user),
        });
        
        const data = await res.json();
        // 通过res.ok判断请求是否成功(状态码200-299)
        if(!res.ok){
            dispatch(signInFailure(data.message || '登录失败'));
            return;
        }
        dispatch(signInSuccess(data));
        navigate('/upload');
      } catch(error){
        dispatch(signInFailure(error.message));
      }
  } ;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:20:27