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

AWS上React应用调用Node.js接口出现Failed to fetch错误排查

问题描述

我有一个基于Vite.js(React)的前端应用,以及一个查询MySQL数据库的Node.js后端服务,本地运行完全正常,但部署到AWS平台后出现“Failed to fetch”错误。不确定问题出在CloudFront、Nginx、3001端口的Node.js服务,还是HTTPS网站发起HTTP请求这几个环节,想明确需要修复的具体点。目前Node.js接口通过ip:3001/api和localhost:3001/api都能正常访问。


App.tsx中的Fetch代码

useEffect(() => {
  fetch("http://localhost:3001/api")
    .then((res) => res.json())
    .then((data) => setData(data.message))
    .catch(rejected => {
              console.log(rejected);
              })
}, []);

Node.js服务代码(运行在3001端口)

import express from "express";
import cors from "cors";
const app = express();

app.use(express.json());
app.use(cors())

const PORT = process.env.PORT || 3001;

app.get("/api", (req, res) => {
var allowedOrigins = ['https://example.com']
res.header('Access-Control-Allow-Origin', allowedOrigins)
  res.json({
  "message": "dynamic json",
  "mytest": "server"
        })
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
  console.log(`Server running`);
});

Nginx conf.d配置

server {
  listen 80;
  listen 443;
  server_name _;

  location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3001;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
  }
}

问题定位与修复方案

1. 前端Fetch地址错误(核心问题)

前端代码硬编码http://localhost:3001/api,部署后前端运行在用户浏览器中,localhost指向用户本地机器而非AWS服务器的后端服务,这是请求失败的直接原因。

修复:

  • 改用相对路径:将fetch("http://localhost:3001/api")改为fetch("/api"),请求会自动转发到当前前端域名的/api路径,再通过Nginx代理到后端。
  • 或用环境变量配置:在Vite的.env文件中设置VITE_API_URL=/api,代码中使用fetch(import.meta.env.VITE_API_URL)。

2. HTTPS与HTTP混合请求问题

如果前端部署在HTTPS域名(如CloudFront分发的HTTPS地址),直接请求HTTP的localhost:3001会被浏览器拦截(混合内容限制),也会触发“Failed to fetch”。

修复:

  • 借助Nginx的HTTPS代理,前端用相对路径或HTTPS域名路径即可规避此问题。

3. CORS配置冲突问题

Node.js代码同时启用全局cors()中间件和接口单独设置Access-Control-Allow-Origin头,易导致CORS头冲突。

修复:

  • 统一CORS配置,保留全局中间件并指定允许的源:
app.use(cors({
  origin: 'https://example.com' // 替换为你的前端实际域名
}));
  • 删除接口中单独设置的res.header('Access-Control-Allow-Origin', allowedOrigins),避免重复设置头信息。

4. Nginx配置补充

当前Nginx监听443端口但未配置SSL证书,部署到AWS后需确保443端口有正确的SSL证书(如AWS Certificate Manager提供的证书),否则HTTPS请求会失败。

补充配置示例:

server {
  listen 80;
  server_name _;
  # HTTP请求重定向到HTTPS
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl;
  server_name _;

  # 配置SSL证书路径(AWS可用ACM证书,或指定本地证书文件)
  ssl_certificate /path/to/your/cert.pem;
  ssl_certificate_key /path/to/your/key.pem;

  location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3001;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
  }

  # 托管前端静态文件(若Nginx同时负责前端部署)
  location / {
    root /path/to/your/react/build;
    try_files $uri $uri/ /index.html;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:15:22