Docker Compose 中 Nginx 和 NodeJS 的 CORS 问题

问题描述 投票:0回答:1

我尝试创建一个使用 Nginx 和 NodeJS 运行 React 应用程序的 docker compose,我可以在 React 中看到我的主页,但出现以下错误:

跨域请求被阻止:同源策略不允许读取远程资源http://backend:3000/message。 (原因:CORS请求不成功)。

这就是我从 React 调用 API 的方式:

useEffect(() => {
    fetch('http://backend:3000/message')
      .then(response => response.text())
      .then(data => setMessage(data))
      .catch(error => console.error('Error al obtener el mensaje:', error));
  }, []); 

这是我的 NodeJS Dockerfile:

FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]

这是我的 React Dockerfile:

FROM node:20.11.1-alpine3.19 as build
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build

FROM nginx:1.25.4-alpine3.18
COPY --from=build /app/dist /usr/share/nginx/html
COPY default.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

这就是我创建conf.d的方式:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Accept,Content-Type';
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

这是我的 docker-compose.yaml:

version: '3'

services: 

  backend:
    image: pedrocastro2001/back-end-node
    container_name: backend
    networks: 
      - node-network
    ports: 
      - "3000:3000"

  frontend:
    image: pedrocastro2001/front-end-react
    container_name: frontend
    networks: 
      - node-network
    ports: 
      - "5173:80"
  
networks: 
  node-network:
    driver: bridge

我无法弄清楚我的配置出了什么问题,如果有任何帮助,我将非常感激。

reactjs node.js docker nginx docker-compose
1个回答
-1
投票

CORS 配置应该在后端代码中设置,但现在您实际上在前端组件中设置 CORS。我建议您使用

proxy_pass
将外部请求转换为本地主机请求。

useEffect(() => {
    fetch('/api/message')
      .then(response => response.text())
      .then(data => setMessage(data))
      .catch(error => console.error('Error al obtener el mensaje:', error));
  }, []); 
server {
    listen       80;
    listen  [::]:80;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location /api { # Probably a prefix for your API routes
        proxy_pass http://backend:3000;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.