从Node服务器GET路由获取数据时JSON解析错误求助
问题:GET请求Node服务器返回HTML而非JSON,POST请求正常运行
现象与报错
- 从Node服务器GET路由获取数据时触发JSON解析错误,POST请求可正常执行
- 报错信息:
localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON useGetConversations.js:16
相关代码
Zustand状态管理代码
import { create } from "zustand"; const useConversation = create((set) => ({ selectedConversation: null, setSelectedConversation: (selectedConversation) => set({ selectedConversation }), messages: [], setMessages: (messages) => set({ messages }), })); export default useConversation;
疑似出错的useGetConversations代码
import { useEffect, useState } from "react"; import toast from "react-hot-toast"; const useGetConversations = () => { const [loading, setLoading] = useState(false); const [conversations, setConversations] = useState([]); useEffect(() => { const getConversations = async () => { setLoading(true); try { const res = await fetch("/users"); console.log(res);//the res is printed in console with bodyUsed as true const data = await res.json();//this is never executed ig if (data.error) { throw new Error(data.error); } setConversations(data); } catch (error) { toast.error(error.message); } finally { setLoading(false); } }; getConversations(); }, []); return { loading, conversations }; }; export default useGetConversations;
已完成的排查操作
- Vite代理配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { port: 3000, proxy: { "/api": { target: 'http://localhost:5000', changeOrigin: true, secure: false }, }, }, })
- 后端路由添加日志,POST路由有打印输出,GET路由无日志,推测请求未发送到后端
- Postman测试后端GET请求可正常返回JSON数据
解决方案
核心问题
你的fetch("/users")请求没有匹配Vite代理规则,被Vite开发服务器直接处理,返回了前端的index.html页面,这就是解析JSON时遇到<符号报错的原因。
具体修复步骤
修改前端请求路径
把fetch("/users")改成fetch("/api/users"),让请求匹配Vite的/api代理前缀,自动转发到后端http://localhost:5000/users。可选:调整后端路由或代理规则
如果后端的GET路由实际是/api/users,可以保持前端请求路径不变,在Vite代理配置中添加路径重写:
proxy: { "/api": { target: 'http://localhost:5000', changeOrigin: true, secure: false, pathRewrite: { "^/api": "" } // 转发时去掉/api前缀 }, }
- 增强错误处理(可选)
在解析JSON前先检查响应状态,提前捕获请求异常:
const res = await fetch("/api/users"); if (!res.ok) { throw new Error(`请求失败,状态码:${res.status}`); } const data = await res.json();
验证方法
修改后查看后端日志是否出现GET请求的打印,同时在前端控制台查看res.url属性,确认请求路径已正确转发到后端地址。
内容的提问来源于stack exchange,提问作者Rajbir
相关产品推荐
相关产品推荐

