React容器无法通过fetch/axios访问Node API容器的问题求助
问题分析与解决建议
核心问题在于:React应用是在用户浏览器中运行的,而非React容器内部。http://node-api:9000是Docker Compose内部的服务域名,仅能在容器所在的Docker网络中解析,浏览器无法识别这个域名,因此会出现网络错误,CORS报错只是表象。
解决方法
方法一:直接使用远程主机地址调用API
- 修改React中的API请求URL,替换为远程主机的公网IP/域名+API端口:
const handleContentClick = async () => { let url = `http://<远程主机IP>:9000/api/content`; const response = await fetch(url); const data = await response.json(); } - 后端明确配置允许React应用的源:
const express = require("express"); const cors = require("cors"); const app = express(); // 替换为React应用的访问地址(如http://<远程主机IP>:3000) app.use(cors({ origin: "http://<远程主机IP>:3000" })); - 确保远程主机防火墙开放9000(API)和3000(React)端口。
方法二:使用Nginx反向代理(生产环境推荐)
通过Nginx统一转发静态资源和API请求,让浏览器只和Nginx通信,彻底避免跨域问题:
- 修改
docker-compose.yml,新增Nginx服务:version: '3.8' services: node-api: build: ./node-api restart: on-failure # 无需暴露端口到主机,仅内部网络访问 react-app: build: ./react-app restart: on-failure # 无需暴露端口到主机 nginx: image: nginx:alpine ports: - 80:80 volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf # 挂载React构建后的静态文件到Nginx - ./react-app/build:/usr/share/nginx/html depends_on: - node-api - react-app - 创建
nginx.conf配置文件:server { listen 80; # 处理React静态页面路由 location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; } # 转发API请求到node-api服务 location /api { proxy_pass http://node-api:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } - 修改React中的API请求为相对路径:
const handleContentClick = async () => { let url = `/api/content`; const response = await fetch(url); const data = await response.json(); }
补充说明
容器内用curl或node能正常访问API,是因为容器处于Docker内部网络中,可以解析node-api这个服务域名;而浏览器运行在用户本地网络,无法访问Docker内部的域名映射,这就是本地运行正常、远程部署出错的根本原因。
内容的提问来源于stack exchange,提问作者Marko Stanković
相关产品推荐
相关产品推荐

