前端Fetch请求后端返回HTML而非JSON的问题求助
问题排查与解决步骤
1. 检查Express后端的路由顺序
Express路由是从上到下匹配的,如果静态文件托管代码(比如express.static)放在API路由之前,或者API路由之后有兜底返回index.html的逻辑,就会导致未匹配的API请求被返回前端页面。
正确的代码顺序应该是:
- 先定义所有API路由
- 再托管前端静态文件(前后端同部署场景)
- 最后加兜底路由返回index.html(仅用于前端SPA路由)
示例代码:
// 先写API路由 app.get('/api/users', (req, res) => { res.json([{id:1, name:'Alice'}, {id:2, name:'Bob'}]); }); // 再托管前端静态文件(同部署时用) app.use(express.static(path.join(__dirname, 'client/dist'))); // 最后兜底返回index.html(仅处理前端路由) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/dist', 'index.html')); });
2. 确认前端fetch请求地址与跨域配置
- 检查跨域问题:如果前后端端口不同,必须给Express配置CORS中间件。
安装并启用:npm install corsconst cors = require('cors'); app.use(cors()); - 检查fetch的URL是否正确,比如是否遗漏后端域名/端口,或者路径拼写错误(比如写成
/users而非/api/users)。示例正确请求:// 开发环境下,后端3000端口、前端5173端口的情况 fetch('http://localhost:3000/api/users') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
3. 验证Vite代理配置是否生效
如果用Vite代理API请求到后端,确保vite.config.js配置正确,且重启过Vite服务:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { proxy: { '/api': { target: 'http://localhost:3000', // 后端地址 changeOrigin: true } } } });
配置后前端可直接用fetch('/api/users'),无需写完整域名。
4. 直接测试后端API接口
用curl或Postman直接请求后端的/api/users接口,确认返回的是JSON而非HTML:
curl http://localhost:3000/api/users
如果这里返回的就是HTML,问题肯定出在后端路由配置。
5. 排查浏览器缓存
强制刷新页面(Ctrl+F5)或用无痕模式测试,排除旧响应缓存的影响。
内容的提问来源于stack exchange,提问作者Anan Ma
相关产品推荐
相关产品推荐

