CORS Anywhere 跨域代理搭建教程

在前端开发中,浏览器的同源策略会阻止跨域请求。CORS Anywhere 是一个 Node.js 反向代理服务,可以在请求中添加 CORS 头,让前端应用能够访问任意 API。虽然公共的 CORS 代理存在安全和性能问题,但在搬瓦工 VPS 上自建私有 CORS 代理,可以完全控制访问权限和性能。

一、安装 Node.js

curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install nodejs -y
node -v

二、安装 CORS Anywhere

mkdir -p /opt/cors-proxy && cd /opt/cors-proxy
npm init -y
npm install cors-anywhere

2.1 创建服务器文件

创建 server.js

const cors_proxy = require('cors-anywhere');

// 配置选项
const host = '127.0.0.1';
const port = 8088;

cors_proxy.createServer({
  originWhitelist: [
    'https://your-frontend.example.com',
    'http://localhost:3000',
    'http://localhost:5173',
  ],
  requireHeader: ['origin', 'x-requested-with'],
  removeHeaders: ['cookie', 'cookie2'],
  redirectSameOrigin: true,
  httpProxyOptions: {
    xfwd: false,
  },
  // 速率限制配置
  rateLimit: 50,  // 每分钟最大请求数
}).listen(port, host, function() {
  console.log('CORS Anywhere 代理运行在 ' + host + ':' + port);
});

三、使用 PM2 管理进程

npm install -g pm2
pm2 start /opt/cors-proxy/server.js --name "cors-proxy"
pm2 save
pm2 startup

四、Nginx 反向代理

server {
    listen 80;
    listen 443 ssl http2;
    server_name cors.example.com;

    ssl_certificate /etc/letsencrypt/live/cors.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/cors.example.com/privkey.pem;

    # 速率限制
    limit_req_zone $binary_remote_addr zone=cors_limit:10m rate=10r/s;

    location / {
        limit_req zone=cors_limit burst=20 nodelay;

        proxy_pass http://127.0.0.1:8088;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 安全头部
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "DENY" always;
    }
}
nginx -t && systemctl reload nginx

五、使用方法

在前端代码中,将 API 请求的 URL 前加上你的代理地址:

// 原始请求(被 CORS 阻止)
fetch('https://api.third-party.com/data')

// 通过 CORS 代理请求
fetch('https://cors.example.com/https://api.third-party.com/data', {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  }
})

六、安全加固

6.1 IP 白名单

# 在 Nginx 中限制访问源
location / {
    # 只允许特定来源
    if ($http_origin !~* "^https://(your-frontend\.example\.com|localhost)") {
        return 403;
    }
    proxy_pass http://127.0.0.1:8088;
}

6.2 请求大小限制

# 限制代理请求的大小
client_max_body_size 1M;
proxy_read_timeout 10s;
proxy_connect_timeout 5s;

6.3 日志监控

# 查看代理日志
pm2 logs cors-proxy

# 监控请求频率
tail -f /var/log/nginx/access.log | grep cors.example.com

七、Nginx 原生 CORS 代理方案

对于简单的 CORS 需求,可以直接用 Nginx 作为反向代理,无需 Node.js:

server {
    listen 443 ssl http2;
    server_name cors.example.com;

    location /api/ {
        # 添加 CORS 头
        add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type' always;

        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 86400;
            return 204;
        }

        # 代理到目标 API
        proxy_pass https://api.third-party.com/;
        proxy_set_header Host api.third-party.com;
        proxy_ssl_server_name on;
    }
}

总结

自建 CORS 代理比使用公共代理更安全、更可靠。在搬瓦工 VPS 上部署 CORS Anywhere 或使用 Nginx 原生反向代理都是可行方案。务必配置好白名单和速率限制,避免被滥用。对于需要更完善 API 网关功能的场景,可以考虑 OAuth2 认证服务器

选购搬瓦工 VPS 请查看 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的折扣,通过 bwh81.net 进入官网购买。

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。