将前端代码编译生成dist目录后,部署到宝塔的nginx上,绑定域名,访问时,报错:CORS

将前端代码编译生成dist目录后,部署到宝塔的nginx上,绑定域名,访问时,报错:CORS

从错误信息来看,这是一个典型的跨域(CORS)问题。错误显示访问 http://localhost:3000/api/match_summary 时被CORS策略阻止,因为 ‘Access-Control-Allow-Origin’ header 的值 http://localhost:8080 与实际源 https://www.ijeko.com 不匹配。

以下是解决方案:

1、在 Nginx 配置文件中添加跨域相关配置:

server {
listen 80;
server_name www.ijeko.com; # 替换成你的域名

location /api {
# 代理到后端服务
proxy_pass http://localhost:3000;

# 添加跨域配置
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header Access-Control-Allow-Credentials 'true';

# 处理 OPTIONS 请求
if ($request_method = 'OPTIONS') {
return 204;
}
}

location / {
root /path/to/your/dist; # 替换成你的dist目录路径
index index.html;
try_files $uri $uri/ /index.html;
}
}

2、修改前端 API 请求地址,将 baseURL 改为相对路径:

// 修改所有API请求路径
// 原来的:
const response = await fetch('http://localhost:3000/api/match_summary');

// 改为:
const response = await fetch('/api/match_summary');

3、重启 Nginx 服务:

nginx -s reload

这样配置后:

  1. 前端代码中使用相对路径访问 API
  2. Nginx 将 /api 开头的请求代理到后端服务
  3. Nginx 添加了必要的跨域响应头
  4. 静态文件(dist目录)由 Nginx 直接提供服务

:::tip{title=”提示”}
如果仍有问题,请检查:

  1. Nginx 配置文件是否正确加载
  2. 后端服务(localhost:3000)是否正常运行
  3. 域名解析是否正确指向服务器
  4. 服务器防火墙是否放行了相应端口

:::