CORS在dockerized Django REST + Angular项目中被封锁

时间:2018-11-20 23:21:44

标签: django angular docker django-rest-framework django-cors-headers

我决定今天对现有的Django REST + Angular应用进行docker化。网站正在按原样显示,但CORS请求被阻止。

  

CORS策略已阻止从来源“ http://localhost:8000/branches/1”访问“ http://localhost:3000”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

Angular App使用Nginx进行了码头化。我在进度中使用了this教程(下面列出了docker + compose文件)。

奇怪的是,我之前有这个问题,并通过使用 djang-cors-headers 包解决了。与CORS_ORIGIN_ALLOW_ALL = True一起,这似乎不再能解决问题。

这是否可以与应用程序现在在容器中运行有关?我在下面提供了项目的dockerfile以及docker-compose文件。不确定它们是否相关。

Angular项目的Dockerfile:

FROM tiangolo/node-frontend:10 as build-stage
WORKDIR /app

COPY package*.json /app/
RUN npm install

COPY ./ /app/
ARG configuration=production
RUN npm run build -- --output-path=./dist/out --configuration $configuration

# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15
COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html

# Copy the default nginx.conf provided by tiangolo/node-frontend
COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.confenter

用于Django REST项目的Dockerfile:

# Pull base image
FROM python:3.7

# Set environment varibles
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# create root directory
RUN mkdir /web

# set working directory
WORKDIR /web

# Coppy current directory contents into the container
ADD . /web/

# Install any needed packages in requirements.txt
RUN pip install -r requirements.txt

还有docker-compose.yml文件:

version: '3'

services:
  db:
    image: mysql:5.7
    restart: always
    container_name: db
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_PORT=3306  # cannot change this port to other number
      - MYSQL_ROOT_HOST=%
      - MYSQL_DATABASE=test
      - MYSQL_USER=belter
      - MYSQL_PASSWORD=belter_2017
      - MYSQL_ROOT_PASSWORD=123456_abc
    ports:
      - '3302:3306'

  web:
    build: ./orca/
    restart: always
    command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    container_name: web
    volumes:
      - ./orca:/code
    ports:
      - '8000:8000'
    depends_on:
      - db

  angular:
    build: ./ng-orca-new/
    container_name: angular
    ports:
      - '3000:80'

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是由于nginx阻止了请求。在该层再次添加标题,产生以下nginx.conf:

server {
  listen 80;
  location / 
    add_header "Access-Control-Allow-Origin" "*";
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
    add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin';

    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}