React项目调用API获笔记遇401未授权及map函数报错求助
React笔记应用API请求与渲染问题排查
1. GET http://localhost:5000/api/notes/fetchallnotes 返回401 (Unauthorized)
排查方向与解决方案:
- Token传递格式验证:确认
getNotes函数中请求头的写法符合后端要求,多数后端需要Bearer前缀,示例:axios.get('/api/notes/fetchallnotes', { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) - Token有效性检查:用Postman直接携带token发送请求,若仍返回401,说明token已过期或无效,需重新登录获取新token;若Postman请求正常,再排查前端token的读取逻辑。
- LocalStorage键名校验:确认
localStorage.getItem("token")的键名与登录时存储的键名完全一致,避免拼写错误。 - 后端CORS配置:检查后端是否允许
Authorization请求头跨域,需在CORS设置中添加Access-Control-Allow-Headers: Authorization。
2. TypeError: notes.map is not a function
排查方向与解决方案:
- Context初始状态设置:确保Context中notes的初始值为数组
[],而非null或undefined,示例:const [notes, setNotes] = useState([]) - API返回数据解析:检查
getNotes函数中后端返回的数据结构,若后端返回的是包含数组的对象(如{ data: { notes: [...] } }),需正确提取数组部分赋值:const response = await axios.get(...) setNotes(response.data.notes) // 而非直接setNotes(response.data) - 请求失败时的状态兜底:在
getNotes的错误捕获逻辑中,将notes重置为空数组,避免请求失败后notes变为非数组类型:catch (error) { setNotes([]) // 其他错误处理逻辑 } - 渲染前的类型校验:在调用map前添加数组类型判断,避免非数组触发报错:
{Array.isArray(notes) ? notes.map((note) => ( <Noteitem key={note._id} updateNote={updateNote} note={note} showAlert={props.showAlert} /> )) : null}
相关代码片段
NoteState.js
import React, { useContext, useEffect, useRef, useState } from "react"; import noteContext from "../Context/notes/noteContext"; import Noteitem from "./Noteitem"; import AddNote from "./AddNote"; import { useNavigate } from "react-router-dom"; const Notes = (props) => { const context = useContext(noteContext); let navigate = useNavigate(); const { notes, getNotes, editNote } = context; useEffect(() => { if (localStorage.getItem("token")) { getNotes(); } else { navigate("/"); } // eslint-disable-next-line }, []); // ... return ( <> {/* ... */} <div className="row my-3"> <h2>Your Notes</h2> <div className="container mx-2"> {notes.length === 0 && "No notes to display."} </div> {notes.map((note) => { return ( <Noteitem key={note._id} updateNote={updateNote} note={note} showAlert={props.showAlert} /> ); })} </div> </> ); }; export default Notes;
Notes.js
import React, { useContext, useEffect, useRef, useState } from "react"; import noteContext from "../Context/notes/noteContext"; import Noteitem from "./Noteitem"; import AddNote from "./AddNote"; import { useNavigate } from "react-router-dom"; const Notes = (props) => { const context = useContext(noteContext); let navigate = useNavigate(); const { notes, getNotes, editNote } = context; useEffect(() => { if (localStorage.getItem("token")) { getNotes(); } else { navigate("/"); } // eslint-disable-next-line }, []); // ... return ( <> {/* ... */} <div className="row my-3"> <h2>Your Notes</h2> <div className="container mx-2"> {notes.length === 0 && "No notes to display."} </div> {notes.map((note) => { return ( <Noteitem key={note._id} updateNote={updateNote} note={note} showAlert={props.showAlert} /> ); })} </div> </> ); }; export default Notes;
内容的提问来源于stack exchange,提问作者ADITYA RAJ
相关产品推荐
相关产品推荐

