You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地Vite项目API请求404与跨域问题,部署后Axios报错求助

问题排查与解决方案

一、本地CORS + 404错误处理

1. 优先解决404错误

404是核心问题,CORS报错可能是接口不存在导致的次生问题:

  • 核对后端Express路由路径与前端Axios请求路径完全一致,比如后端定义/api/user/list,前端不能写成/user/list或/api/users/list
  • 确认后端服务在指定端口正常启动,前端Axios的baseURL需精准指向该端口(如http://localhost:3000,端口号不能写错)
  • 用Postman直接请求后端接口,验证是否返回200状态码,排除路由逻辑或数据库连接故障

2. CORS配置修正

若404解决后仍有CORS报错,调整Express的CORS中间件:

  • 确保CORS中间件在路由加载前执行,示例代码:
    const cors = require('cors');
    const app = express();
    
    // 先配置CORS
    app.use(cors({
      origin: ['http://localhost:5173'], // 前端本地服务地址(Vite默认端口5173)
      credentials: true // 需携带Cookie/Authorization头时开启
    }));
    // 再加载路由
    app.use('/api', require('./routes'));
    
  • 禁止同时使用通配符*和credentials: true,这会导致CORS规则失效
  • 本地开发可通过Vite代理绕过浏览器CORS限制(见下文Vite配置部分)

二、cPanel部署后本地无法查看修改的问题

  • 本地代码与cPanel部署代码是独立副本,修改本地代码后需重新执行npm run build生成最新dist文件夹,再通过FTP或cPanel文件管理器上传替换public_html目录下的旧文件
  • 上传完成后强制刷新浏览器(Ctrl+Shift+R),避免加载缓存的静态资源

三、部署后Axios错误预防

1. 前端Axios多环境配置

通过环境变量区分开发/生产环境的API地址:

// axios实例配置
import axios from 'axios';
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
  timeout: 10000
});

在项目根目录创建环境配置文件:

// .env.development(本地开发)
VITE_API_URL=http://localhost:3000/api

// .env.production(生产环境)
VITE_API_URL=https://your-domain.com/api // 替换为cPanel绑定的域名

2. cPanel后端部署注意事项

  • 使用cPanel的Node.js Selector配置后端启动文件(如server.js),端口由cPanel自动分配,禁止硬写端口号
  • 确保后端路由前缀(如/api)与前端生产环境的baseURL完全匹配
  • 检查cPanel防火墙是否开放后端应用端口,或通过域名反向代理将请求指向后端服务

四、关键代码参考

后端Express核心配置

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();

// CORS多环境适配
const corsOptions = {
  origin: process.env.NODE_ENV === 'production' 
    ? 'https://your-domain.com' 
    : 'http://localhost:5173',
  credentials: true
};
app.use(cors(corsOptions));

// 解析请求体
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 挂载路由
app.use('/api', require('./routes/auth'));

// 数据库连接
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/your-db')
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.error('数据库连接失败:', err));

// 启动服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`服务运行在端口 ${PORT}`));

Vite本地代理配置(绕过CORS)

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react'; // 根据使用的框架调整

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  }
});

配置后,前端请求/api/user/list会自动代理到http://localhost:3000/api/user/list,绕过浏览器CORS限制


内容的提问来源于stack exchange,提问作者pratik bhattarai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:36:57