首页 > 解决方案 > Flask Restplus Swagger 没有在 Nginx 后面加载

问题描述

我有一个 Flask API 和一个使用 Flask Restplus 生成的 Swagger UI。API 在 Nginx 容器后面的 Docker 容器中运行,该容器通过 HTTP 为其提供服务。

这是确认 API 正在运行的健康检查端点:https ://mobydq.net/mobydq/api/v1/health

{"message":"MobyDQ API running in production mode"}

但是,应该在以下 URL 加载的 Swagger 根本不会加载:https ://mobydq.net/mobydq/api/doc

这是 Nginx 的配置:

http {
    upstream api  {
      server api:5434;
    }

    upstream app {
      server app:3000;
    }

    # Server for https
    server {
      listen       443 ssl http2;
      server_name  mobydq.net;

      ssl_certificate      /etc/letsencrypt/live/mobydq.net/fullchain.pem;
      ssl_certificate_key  /etc/letsencrypt/live/mobydq.net/privkey.pem;

      # Location for MobyDQ Flask API
      location /mobydq {
        limit_req zone=default burst=20;
        proxy_pass http://api;
        proxy_redirect   off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
      }

      # Location for MobyDQ Web App
      location / {
        limit_req zone=default burst=20;
        proxy_pass http://app;
        proxy_redirect   off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
      }
    }

    # Default server to redirect http requests to https
    server {
      listen 80 default_server;
      server_name mobydq.net;
      listen [::]:80 default_server;

        location ~ /.well-known {
            root /var/www/letsencrypt;
        }
        location / {
            return 301 https://$host$request_uri;
        }
    }
}

知道为什么 Swagger 没有加载吗?我查看了加载页面时发送的 http 请求,但没有太大帮助。我只能看到图标加载:

enter image description here

我还查看了控制台并看到了一个错误,但我无法说出它的含义:

enter image description here

标签: nginxflaskhttpsswaggerflask-restplus

解决方案


The problem was that Nginx did not properly redirect the http requests when trying to get the resources from Swagger (the JSON configuration file in particular).

The issue has been fixed by changing the Nginx configuration as follow:

[...]
  # Location for MobyDQ Flask API
  location ~ ^/(mobydq|swaggerui) {
    limit_req zone=default burst=20;
    proxy_pass http://api;
    proxy_redirect   off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
[...]

推荐阅读