You need to enable JavaScript to run this app. React对接MongoDB出现map undefined与代理EPROTO错误
优惠活动
大模型
产品
解决方案
定价
更多

React对接MongoDB出现map undefined与代理EPROTO错误

问题解决方案

1. 代理错误 Could not proxy request /notes from localhost:3000 to https://localhost:3001/(错误码EPROTO)解决

这个错误的核心原因是代理协议和后端服务协议不匹配,按以下步骤排查:

  • 检查前端代理配置(通常是package.json的proxy字段,或者src/setupProxy.js配置文件),如果后端3001端口运行的是HTTP服务,把代理目标地址的https改为http,即修改为http://localhost:3001
  • 如果后端确实开启了HTTPS,在代理配置中添加secure: false配置项,关闭本地自签名证书的校验逻辑
  • 确认后端服务已经正常启动在3001端口,没有被其他进程占用

2. TypeError: Cannot read property 'map' of undefined 解决

这个错误是因为请求逻辑异常时,notes状态被覆盖为undefined导致的,你的代码存在两个问题:

  • useEffect没有加依赖数组,会无限重复触发fetch请求
  • 当fetch请求返回的响应状态码不是2xx时,第一个then没有返回值,第二个then拿到的参数为undefined,执行setNotes(undefined)后,notes变为非数组类型,调用map方法就会报错

修复后的完整代码:

import { useState, useEffect } from 'react'

function Notes(){
    const [notes, setNotes] = useState([{
        name: '',
        email: '',
        phone: '',
        message: ''
    }])

    useEffect(() => {
        fetch("/notes")
        .then(res => {
            if(res.ok) {
                return res.json()
            }
            throw new Error('请求响应异常')
        })
        .then(jsonRes => {
            // 校验返回值为数组再更新状态
            if(Array.isArray(jsonRes)) {
                setNotes(jsonRes)
            }
        })
        .catch(err => {
            console.error('笔记请求失败:', err)
        })
    }, []) // 空依赖数组,组件挂载时仅执行一次

    return <div className="container">
        <h1>Notes page</h1>
        {/* 可选链兜底,避免非数组场景报错 */}
        {notes?.map((note, index) => 
            <div key={index}>
                <h1>{note.name}</h1>
                <p>{note.email}</p>
                <p>{note.phone}</p>
                <p>{note.message}</p>
            </div>            
        )}
    </div>
}

export default Notes;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:00:04