Vite/React中POST请求报404,Postman仅在React未启动时正常
问题分析与解决方案
核心问题定位
启动Vite React项目后,Express服务器的3000端口被占用,导致服务器无法正常监听请求;或者Vite与Express使用了相同端口,引发端口冲突,最终导致所有请求返回404。
具体解决步骤
1. 分离Vite与Express的端口
确保两个服务使用不同端口,避免冲突:
- 保持Express服务器端口为3000(
index.js中const port = 3000不变)。 - 配置Vite使用默认的5173端口(或其他未被占用的端口):
在React项目根目录新建/修改vite.config.js:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { port: 5173 // 确保与Express的3000端口不同 } })
2. 配置Vite代理优化请求(推荐)
直接请求http://localhost:3000/users会存在跨域风险,同时避免端口冲突问题,配置Vite代理:
修改vite.config.js添加代理规则:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { port: 5173, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } })
同时修改React中的请求URL:
// App.jsx中handleSubmit函数内 const url = "/api/users";
3. 正确启动服务顺序
- 先启动Express服务器:执行
node index.js,确认控制台输出Example app listening on port 3000。 - 再启动React项目:执行
npm run dev,确认Vite在5173端口正常启动。 - 此时Postman请求
http://localhost:3000/users、React应用提交表单均能正常响应。
4. 额外排查点
- 检查Express的数据库连接
connectToDB()是否成功:可在该函数内添加日志输出,确认数据库连接状态。 - 确认Express服务器启动时无端口占用报错:若控制台出现
EADDRINUSE提示,说明端口已被其他进程占用,需清理占用端口的进程后重新启动。
内容的提问来源于stack exchange,提问作者Hassan
相关产品推荐
相关产品推荐

