我正在使用基于Webpack / vue的前端方法(在构建后使用nginx服务)和Flask应用程序作为后端来构建应用程序。两者都包含在单独的Docker容器中,并且可以通过使用docker-compose文件构建网络来进行通信。
除一件事情外,其他所有方法都运行良好:Docker容器具有不同的端口,因此被归类为交叉源,这意味着只有将Access-Control-Allow-Origin
设置为*
才能读取来自后端的响应。我在Flask中使用以下方法做到这一点:
@app.after_request
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
header['Access-Control-Allow-Headers'] = 'content-type, session_id'
header['Access-Control-Allow-Methods'] = 'DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT'
return response
这很完美:当我在Docker容器之外运行后端和前端时,响应头实际上就是我设置的头。
但是在Docker容器中,以某种方式从Flask响应中删除了Access-Control-Allow-Origin
。
这是我的docker文件和docker-compose文件:
后端:
FROM python:3.6
RUN pip install --upgrade pip && pip install pipenv
COPY ./backend /app
# Pipfile and Pipfile.lock needed with --system flag
COPY ./backend/Pipfile /app
WORKDIR /app
RUN mkdir -p /app/uploads
# RUN pipenv lock && pipenv install --system --deploy --ignore-pipfile
RUN pipenv install --system --deploy --skip-lock
EXPOSE 5000
# Run the app
CMD ["python", "app.py"]
前端:
# Stage 1: Build
FROM node AS build
WORKDIR /usr/src/app
# Install all dependencies for production
COPY frontend/package.json .
RUN npm install
ENV NODE_ENV="production"
# Bundle app source
COPY frontend/ .
RUN npm run build
# Stage 2: Production environment
FROM nginx:alpine
# Copy built VUE app to be served by nginx
COPY --from=build /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Docker撰写:
version : '3'
services:
frontend:
image: ***
build:
context: .
dockerfile: Dockerfile.frontend
image: ***
ports:
- "9080:80"
networks:
- app_net
backend:
image: ***
build:
context: .
dockerfile: Dockerfile.backend
image: ***
networks:
- app_net
ports:
- "6852:6852"
expose:
- "6852"
# Build internal network, otherwise frontend and backend
# can't communicate on MacOS
networks:
app_net:
driver: "bridge"
是否有任何手动设置CORS标头或确保未将其删除的想法?