CORS 阻止来自 Dockerized React 项目的 API 调用

Tim*_*ins 5 node.js docker reactjs dockerfile docker-compose

我在运行一个独立的 dockerized React 应用程序时遇到问题,该应用程序对 dockerized Node.js 微服务进行 Restful 调用。我遇到的问题是请求被 CORS 策略阻止,并出现以下错误:

Access to XMLHttpRequest at 'http://localhost:3001/api/restaurants/' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value '"http://172.28.1.1:3000"'.

有一个 url 环境变量,我用它在容器运行时设置接受的 cors 标头。我使用相同的技术在两个无头应用程序之间发出请求。React 有什么东西意味着这行不通吗?

我尝试在 docker-compose 中设置 IP 地址,以便作为 CORSHEADER 环境变量传入。我在下面添加了相关代码。

docker-compose.yml

version: '3'

services:
  web-ui-service:
    container_name: web-ui-service
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - '.:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - '3000:3000'
    depends_on:
      - restaurant-data-service
    networks:
      vegitable_net:
        ipv4_address: 172.29.1.1

  restaurant-data-service:
    image: timhaydenhawkins/restaurant-data-service
    environment:
      CORSHEADER: "http://172.29.1.1:3000"
    ports:
      - 3001:3001
    networks:
      vegitable_net:
        ipv4_address: 172.29.1.2

networks:
  vegitable_net:
    ipam:
      driver: default
      config:
        - subnet: 172.29.0.0/16
Run Code Online (Sandbox Code Playgroud)

餐厅数据服务中的 Cors 标头设置

module.exports = function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', process.env.CORSHEADER);
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, 
DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested- 
With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
}
Run Code Online (Sandbox Code Playgroud)

这种技术在容器中的无头应用程序中运行良好,但在 React 中使用却存在真正的问题。有任何想法吗?

Fac*_*bos 4

您的节点应用程序应该支持 CORS,如果您使用的是express,您应该在 app.js 文件中添加以下行

const cors = require('cors'); app.use(cors()); app.options('*', cors());