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

MERN栈开发:如何在React前端展示Node.js后端返回的JSON消息

在React前端展示后端JSON错误消息

作为MERN栈新手,要展示后端返回的错误消息,你需要完成以下几步:

1. 添加错误状态管理

在你的Auth组件中,引入useState并新增错误消息状态,用来存储后端返回的提示内容:

import { useState } from 'react';

const Auth = () => {
  // 保留你已有的inputs、isSignup等状态
  const [errorMessage, setErrorMessage] = useState('');
  
  // 组件剩余代码...
}

2. 修改handleSubmit,添加错误捕获逻辑

你当前的sendRequest调用没有处理后端返回的错误状态(如400、404),需要在Promise链中加入catch块,捕获错误并更新状态:

const handleSubmit=(e)=>{
    e.preventDefault()
    console.log(inputs);
    // 每次提交前清空旧的错误消息
    setErrorMessage('');
    
    const request = isSignup ? sendRequest("signup") : sendRequest();
    
    request
      .then((data)=>{
        localStorage.setItem("userId",data.user._id);
        dispath(authActions.login());
        navigate("/blogs");
      })
      .catch((err)=>{
        // 提取后端返回的错误消息,兼容不同请求库的格式
        setErrorMessage(err.response?.data?.message || "请求失败,请稍后重试");
      })
  }

注意:如果你的sendRequest用的是fetch,需要手动判断响应状态是否正常;如果是axios,会自动将4xx/5xx状态码标记为错误,直接在catch中取err.response.data.message即可。

3. 在JSX中渲染错误消息

在表单的合适位置(比如标题下方)添加错误提示组件,当有错误消息时显示:

<form onSubmit={handleSubmit}>
  <Box display="flex" flexDirection={'column'} 
       alignItems='center' 
       maxWidth={400}
       justifyContent={'center'} 
       boxShadow="10px 10px 20px #ccc"
       padding={3}
       margin="auto"
       marginTop={5}
       borderRadius={5}>
    <Typography variant="h2" padding={3} textAlign="center">{isSignup?"Signup":"Login"}</Typography>
    
    {/* 错误消息展示区域 */}
    {errorMessage && (
      <Typography variant="body2" color="error" textAlign="center" marginBottom={2}>
        {errorMessage}
      </Typography>
    )}
    
    {/* 原有的输入框和按钮 */}
    {isSignup && <TextField name="name" onChange={handleChange} value={inputs.name} placeholder='name' margin="normal"/>}
    <TextField name="email" onChange={handleChange} value={inputs.email} type={'email'} placeholder='email' margin='normal'/>
    <TextField name="password" onChange={handleChange} value={inputs.password} type={'password'} placeholder='password' margin='normal'/>
    <Button type="submit" variant="contained" sx={{borderRadius:3,marginTop:3}} color="warning">Submit</Button>
    <Button onClick={()=>setIsSignup(!isSignup)} sx={{borderRadius:3,marginTop:3}}>
      Change to {isSignup ?"Login":"Signup"}</Button>
  </Box>
</form>

补充:确保sendRequest正确处理错误

如果你的sendRequest是基于fetch实现的,需要手动处理错误状态:

const sendRequest = async (endpoint = "login") => {
  const response = await fetch(`/api/auth/${endpoint}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(inputs),
  });
  
  // 检查响应是否正常,否则抛出错误
  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message);
  }
  
  return response.json();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:05:20