簡體   English   中英

CORS在dockerized Django REST + Angular項目中被阻止

[英]CORS blocked in dockerized Django REST + Angular project

我決定今天對現有的Django REST + Angular應用進行docker化。 該網站正在按原樣顯示,但是CORS請求被阻止。

通過CORS策略已阻止從原始地址“ http:// localhost:3000 ”訪問“ http:// localhost:8000 / branches / 1 ”處的XMLHttpRequest:在服務器上沒有“ Access-Control-Allow-Origin”標頭要求的資源。

使用Nginx對有角度的應用進行泊塢化。 我在進度中使用了教程(下面列出了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'

提前致謝!

問題是由於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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM