前端跨域全攻略:从 Vite 代理到 Nginx 生产环境配置实战

1 阅读3分钟

前言

在前后端分离的架构中,跨域(CORS)是我们联调接口时遇到的第一个“拦路虎”。无论是本地开发还是线上部署,掌握跨域的解决手段是前端开发者的基本功。本文将结合 Vite 和 Nginx,深度解析跨域问题的终极解决方案。

一、 什么是跨域?

跨域是由浏览器的同源策略(Same-origin policy)引起的。当一个请求的协议、域名、端口三者中至少有一个不同时,浏览器就会拦截该请求的响应。

注意:跨域请求其实已经发到了服务器,服务器也正常返回了数据,只是浏览器在接收响应时,发现源不匹配,为了安全将其拦截了。


二、 开发环境方案:Vite 反向代理

在开发阶段,我们无法要求后端频繁改动 CORS 配置。此时,利用 Vite 自带的 http-proxy 模块进行转发是最优解。

1. Vite 配置实战

vite.config.js 中配置 server 对象,通过代理服务器绕过浏览器同源策略:

export default defineConfig({
  server: {
    port: 3000,
    cors: true, // 启用并允许任何源(主要用于开发服务器的响应头)
    open: true, // 启动时自动打开浏览器
    
    // 反向代理配置
    proxy: {
      // 场景 A:不移除路径前缀
      // 例如请求 /aPath/login 会转发到 http://33.133.190.116:8100/aPath/login
      "/aPath": {
        target: "http://33.133.190.116:8100", 
        changeOrigin: true, // 必须设置为 true,否则后端无法获取正确的 Host
      },
      
      // 场景 B:重写路径(移除前缀)
      // 例如请求 /bPath/list 会转发到 http://172.16.7.160:9022/list
      "/bPath": {
        target: "http://172.16.7.160:9022",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/bPath/, ""),
      },
    },
  },
})

三、 生产环境方案:Nginx 部署配置

项目上线后,Vite 的代理就不起作用了。此时我们需要在 Nginx 中配置反向代理,让所有的请求由 Nginx 统一分发。

1. Nginx 核心配置文件解析 (nginx.conf)

# 基础全局配置
user nginx;
worker_processes auto; # 自动适配 CPU 核心数
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;

events {
    worker_connections 1024;
    use epoll; # 使用高性能事件驱动模型
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    client_max_body_size 300m; # 支持大文件上传

    # 开启 Gzip 压缩,优化传输性能
    gzip on;
    gzip_comp_level 5;
    gzip_types text/plain text/css application/json application/javascript;

    server {
        listen 80 default_server;
        server_name _; 

        # 静态资源处理
        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
            try_files $uri $uri/ /index.html; # 适配单页面应用路由
        }

        # 代理方案 A:带前缀转发
        # 请求:/aPath/api -> http://33.133.190.116:8100/aPath/api
        location ^~/aPath/ {
            proxy_pass http://33.133.190.116:8100/aPath/;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_read_timeout 3600s;
            proxy_buffering off; # AI 对话场景需关闭缓冲
            chunked_transfer_encoding on;
        }

        # 代理方案 B:抹除前缀转发
        # 请求:/bPath/api -> http://172.16.7.160:9022/api
        location ^~/bPath/ {
            proxy_pass http://172.16.7.160:9022/; 
            proxy_set_header X-Forwarded-For $remote_addr;
        }

        # 禁止访问 .ht 文件
        location ~ /.ht {
            deny all;
        }
    }
}

四、 补充

1. 后端 CORS 配置(简单请求与预检请求)

后端通过在响应头中添加特定字段,告诉浏览器允许该源的访问:

  • Access-Control-Allow-Origin: *
  • Access-Control-Allow-Methods: GET, POST, PUT, DELETE

2. 为什么 Nginx 代理能解决跨域?

因为 “跨域”仅存在于浏览器端。 当你的前端代码请求 Nginx 时,它们同源;Nginx 作为中转站再去请求后端接口,这是 服务器对服务器的通信,不受同源策略限制。