Vite React前端未正确向后端发起API请求问题排查
我正在使用Vite React框架,前端运行在localhost:3000,当尝试向运行在localhost:5000的后端发起API请求时,前端始终在3000端口发起请求而非5000端口。

代码实现
vite.config.js
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { port: 3000, // Frontend runs on port 3000 proxy: { '/api': { target: 'http://localhost:5000/', // Backend running on port 5000 changeOrigin: true, secure: false, }, }, }, });
Login.jsx
const LoginAdmin = () => { const formik = useFormik({ initialValues: { email: '', password: '', }, validationSchema: Yup.object({ email: Yup.string().email('Invalid email address').required('Email is required'), password: Yup.string().required('Password is required'), }), onSubmit: async (values) => { try { const response = await axios.post('/api/admin/login', values); alert('Login successful!'); console.log(response.data); localStorage.setItem('token', response.data.token); } catch (error) { console.error('Login error:', error); alert('Invalid credentials or account not active/approved.'); } }, }); return () };
server.js
const app = express(); // Middleware app.use(cors({ origin: 'http://localhost:3000', // Allow requests from frontend credentials: true, // Allow sending cookies or authentication tokens })); app.use(express.json()); // Connect to MongoDB connectDB(); // Use admin routes app.use('/api/admin', adminRoutes); // Basic route app.get('/', (req, res) => { res.send('Hello from the ES6 backend, DB connected'); }); // Start server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
我已检查表单和Axios请求配置无误,确认后端端点存在且能正确处理请求,也验证了vite.config.js中的代理配置,但问题仍未解决。
排查与解决方案
重启Vite开发服务器
Vite的代理配置修改后必须重启服务器才能生效,这是最容易忽略的点。关闭当前的Vite服务,重新执行npm run dev启动。调整代理目标的斜杠
将vite.config.js中target的末尾斜杠去掉,改为http://localhost:5000,避免路径拼接时出现重复斜杠导致匹配异常:proxy: { '/api': { target: 'http://localhost:5000', changeOrigin: true, secure: false, }, },检查Axios全局配置
确认是否全局设置了Axios的baseURL,如果不小心设成了http://localhost:3000,会直接绕过代理。查看项目中是否有类似以下代码:axios.defaults.baseURL = 'http://localhost:3000';如果有,要么删除该配置,要么改为相对路径
/。验证后端路由匹配
直接用Postman或浏览器访问http://localhost:5000/api/admin/login,确认后端能正常响应这个端点。如果后端返回404,说明后端路由配置有问题,和Vite代理无关。添加路径重写(按需)
如果后端接口的实际路径没有/api前缀(但你的代码中后端是有/api/admin的,所以此步骤可选),可以添加rewrite规则调整路径:proxy: { '/api': { target: 'http://localhost:5000', changeOrigin: true, secure: false, rewrite: (path) => path.replace(/^\/api/, '') }, },注意:你的后端路由是
/api/admin,所以添加此规则会将请求路径改为/admin/login,导致后端无法匹配,因此只有当后端接口无/api前缀时才需要使用。
内容的提问来源于stack exchange,提问作者New MERN Dev

