当 React 前端、Nodejs 后端和 Nginx 使用三个独立的容器时,React 前端出现 CORS 错误

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

docker-compose
文件:

services:
version: "3.8"

#Update the connection among these microservices before starting the container.

services:
  nginx:
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - 80:80
    depends_on:
      - frontend
      - api
    links:
      - frontend
      - api
      
  frontend:
    build: 
      context: ./frontend
      dockerfile: Dockerfile
    ports:
      - 3000:3000
    depends_on:
      - api
    volumes:
      - ./frontend:/app
  
  api:
    build: 
      context: ./api
      dockerfile: Dockerfile
    ports:
      - 5001:5001
    volumes:
      - ./api:/app
    depends_on:
      - db
    links:
      - db

  db:
    image: postgres:15.3-alpine3.18
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: postgres

nginx 默认配置:

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

#access_log  /var/log/nginx/host.access.log  main;

# location / {
#     root   /usr/share/nginx/html;
#     index  index.html index.htm;
# }

location / {
    proxy_pass http://frontend:3000;
}

location /api {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    proxy_pass http://api:5001;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}
}

nginx 的 Dockerfile

FROM nginx:1.25.1-alpine3.17
RUN rm /etc/nginx/conf.d/default.conf COPY default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
Dockerfile for Frontend
FROM node:18.16.1-alpine3.18
RUN mkdir -p /app WORKDIR /app
EXPOSE 3000 CMD echo 1; npm install; echo 2; npm run start

后端 Dockerfile

FROM node:18.16.1-alpine3.18
RUN mkdir -p /app WORKDIR /app
RUN npm install nodemon -g
EXPOSE 5001 CMD echo 1; npm install; echo 2; npm start

代码:

import express, { Application } from "express";
import cors, { CorsOptions } from "cors"; import session from 'express-session'; import Routes from "./routes"; import Database from "./db"; import seedDatabse from './config/seedDB';
export default class Server { constructor(app: Application) { this.config(app); this.syncDatabase(); new Routes(app); }
private config(app: Application): void { const corsOptions: CorsOptions = { origin: ['*'], // credentials: true, };
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: false
}));
}
private async syncDatabase(): Promise<void> { const db = new Database(); await db.sequelize?.sync(); seedDatabse(); } }

前端 api.service.ts 向后端发出请求

export const apiRequests: any = async (uri: string, method: string, body: any) => {
const data = await fetch(`http://localhost/api/${uri}`, {
    method,
    headers: {
        'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : null
})
.then((res: Response) => res.json())
.then((resp: any) => {
    return resp;
});
return data;
};

package.json 的片段

{
  "proxy": "http://api:5001",
  "scripts": { "start": "react-scripts start", 
  "build": "react-scripts build", 
  "test": "react-scripts test", 
  "eject": "react-scripts eject" 
},

我正在使用 4 个不同的 docker:

  1. 前端
  2. 后端
  3. postgres
  4. nginx

两天以来我一直在尝试解决这个问题,但一点运气都没有。 我正在尝试从 React 应用程序向拥有自己的容器的 NodeJS 应用程序发出请求。 第三个容器 nginx 正在连接和管理代理请求。 基本上,我试图从一个容器向另一个容器发出请求,但未能从我的系统中执行此操作。

docker nginx docker-compose dockerfile cors
1个回答
0
投票

也许你的后端 ddockefile 格式错误

//而不是这个

FROM node:18.16.1-alpine3.18
RUN mkdir -p /app WORKDIR /app
RUN npm install nodemon -g
EXPOSE 5001 CMD echo 1; npm install; echo 2; npm start

//这样尝试

FROM node:18.16.1-alpine3.18
RUN mkdir -p /app WORKDIR /app
RUN npm install nodemon -g
EXPOSE 5001
CMD echo 1; npm install; echo 2; npm start

Nginx,更改顺序

试试这个

location /api {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    proxy_pass http://api:5001;
}

location / {
    proxy_pass http://frontend:3000;
}
© www.soinside.com 2019 - 2024. All rights reserved.