Vue 项目跨域解决方案

使用 CORS 和 Proxy 解决 Vue 项目中的跨域问题

问题

Vue 项目开发中遇到跨域请求被浏览器阻止的问题。

解答

CORS 方案

CORS(Cross-Origin Resource Sharing)通过设置 HTTP 响应头来允许跨域请求。这需要后端配置支持。

以 Koa 框架为例:

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  await next();
});

注意:生产环境中应将 Access-Control-Allow-Origin 设置为具体的域名,而不是 *

Proxy 方案

方案一:webpack devServer 代理

vue.config.js 中配置:

module.exports = {
  devServer: {
    host: '127.0.0.1',
    port: 8084,
    open: true,
    proxy: {
      '/api': {
        target: 'http://xxx.xxx.xx.xx:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

在 axios 中配置根路径:

axios.defaults.baseURL = '/api'

方案二:Express 服务端代理

var express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();

app.use(express.static(__dirname + '/'));
app.use('/api', proxy({ 
  target: 'http://localhost:4000', 
  changeOrigin: true
}));

module.exports = app;

方案三:Nginx 反向代理

server {
  listen 80;
  location / {
    root /var/www/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
  }
  location /api {
    proxy_pass http://localhost:4000;
  }
}

关键点

  • CORS 需要后端配置响应头,适合前后端分离且后端可控的场景
  • webpack devServer 代理仅在开发环境有效,上线后需要其他方案
  • Express 或 Nginx 代理可用于生产环境,通过服务端转发请求避免跨域
  • 代理方案的原理是同源请求不受跨域限制,由服务端转发到目标服务器
  • 生产环境建议使用 Nginx 反向代理,性能更好且配置灵活