Angular 8和Flask REST API作为Docker群服务的CORS请求未成功

乔治·D

我有一个包含3个组成部分的小项目:

  • Angular 8 Web应用程序
  • Flask API
  • 一个MongoDB数据库

我试图将所有内容放入Docker,将每个组件都作为映像,并将所有内容收集到我作为群部署的stack.yaml文件中。所有这些只是为了学习Docker以及一切之间的联系。

问题是我无法让CORS工作。现在,我有以下设置:

烧瓶

我认为以下是我的重要组成部分app.py

from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, resources={r"/the_library/*": {"origins": "*", 'methods': 'POST'}})

@app.route('/the_library/upload', methods=["POST"])
def upload_file():
   # here I am using request.files['document'] to get a file and I return a JSON

@app.route("/the_library/find", methods=["POST"])
def find_files():
   # this returns a JSON

if __name__ == '__main__':
    app.run(host='library_api', debug=True, port=5000)

如您所见,我添加flask_cors并启用了CORS。我还添加了以下内容,希望它可以做一些事情(根据我的理解,以下几行都flask_cors可以做相同的事情):

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

角度8

该网络应用由nginx提供。这是Dockerfile:

FROM node:12.6 as builder

# set working directory
WORKDIR /app

# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH

# install and cache app dependencies
COPY package.json package-lock.json /app/
RUN cd /app && npm install
RUN npm install -g @angular/cli

# add app
COPY . /app

# start app
RUN cd /app && npm run build

FROM nginx:1.17.8
RUN rm -rf /usr/share/nginx/html/*
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/dist/TheLibrary/ /usr/share/nginx/html/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Web应用程序已加载(所有静态内容),但是Firefox中的开发者控制台在Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://library_api:5000/the_library/find. (Reason: CORS request did not succeed).尝试调用API时抛出异常

这里也是nginx.conf

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name  library_frontend;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                #
                # Custom headers and headers various browsers *should* be OK with but aren't
                #
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                #
                # Tell client that this pre-flight info is valid for 20 days
                #
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
                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';
            }
            if ($request_method = 'GET') {
                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';
            }
            try_files $uri $uri/ /index.html;
        }

        location ~ /library_api/ {
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                #
                # Custom headers and headers various browsers *should* be OK with but aren't
                #
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                #
                # Tell client that this pre-flight info is valid for 20 days
                #
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
                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';
            }
            if ($request_method = 'GET') {
                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';
            }
        }
    }
}

如您所见,我尝试在2个位置上启用CORS,但是我不确定这种方式,或者如果我什至需要nginx来使此工作正常,那么我很乐意在没有nginx的情况下使其工作。我只是尝试不同的方法来解决CORS问题,并最终遵循了一些使用Nginx的教程。

这是将stack.yaml所有内容链接在一起文件:

version: '3.3'

services:
  api:
    image: library_api
    hostname: library_api
    networks:
      - api_network

  frontend:
    image: library_frontend
    hostname: frontend
    ports:
      - 8080:80
    networks:
      - api_network

networks:
  api_network:
    driver: overlay

我尝试过的事情

我输入了Docker服务,docker exec -it <container> bash并对应该互相访问的服务进行了ping操作,它们很好。

我还尝试通过添加API将API转发到主机

ports:
  - 5000:5000

stack.yaml,但没有任何改变。

通过在我的Flask API中添加CORS,我可以在Docker之外进行所有工作,但是在Docker中我遇到了一些问题,而我却一无所获。

乔治·D

我最终发现了这个问题,对Angular如何使用该应用程序了解得很少。我以为Angular有一个执行API调用的后端,但是实际上,代码被编译并作为一种静态网站使用,因此,我的API调用最终是从客户端完成的AJAX调用。

问题是我docker_api_hostname:port在Angular应用程序中用作我的API调用的基本URL,相反,我应该localhost:port使用该API所使用的端口并将其转发给主机,如问题我尝试过的部分所述。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Angular HTTP和Spring Boot Rest服务

来自分类Dev

Angular HTTP和Spring Boot Rest服务

来自分类Dev

REST API错误“ CORS预检通道未成功”

来自分类Dev

Angular 2/4 和 Jersey REST CORS 问题

来自分类Dev

K8s / Angular CORS发行REST服务器

来自分类Dev

Spring Security REST和Angular

来自分类Dev

构建微服务事件总线和REST api(python / flask)

来自分类Dev

django rest 框架 api 和 angular 2 集成

来自分类Dev

CORS 请求未成功 - Cloudfront 和 ELB over HTTPS

来自分类Dev

Angular Sequential HTTP Rest请求

来自分类Dev

Spring Boot Rest 服务 Angular

来自分类Dev

使用无服务器和DynamoDB Docker化Flask REST API

来自分类Dev

WP REST API v2和Angular $ http POST请求

来自分类Dev

WP REST API v2和Angular $ http POST请求

来自分类Dev

从ANGULAR连接到REST API

来自分类Dev

flutter和Flask REST API之间的数据解析

来自分类Dev

结合 Angular 2 应用服务器和 REST 服务器模块

来自分类Dev

Django和REST API服务于基于计算的请求

来自分类Dev

使用Angular JS,Cors调用symfony 2 rest api

来自分类Dev

使用Angular从Appveyor Rest API获取CORS错误

来自分类Dev

使用Angular从Appveyor Rest API获取CORS错误

来自分类Dev

REST服务和Servlet

来自分类Dev

Spring Rest服务中的Angular File Saver

来自分类Dev

Spring Rest服务中的Angular File Saver

来自分类Dev

$ scope问题与gridOptions,angular-ui-grid和来自服务的REST调用

来自分类Dev

使用Maven,Jersey和Tomcat 8从Intellij运行REST服务

来自分类Dev

使用REST API和javascript前端(例如Angular)进行模型验证的最佳做法

来自分类Dev

使用Django Rest Framework和Angular从API端点发送电子邮件

来自分类Dev

使用Django Rest Framework和Angular从API端点发送电子邮件

Related 相关文章

热门标签

归档