首页 > 解决方案 > 在 Nginx 反向代理后面提供服务时,Swagger UI 无法按预期工作

问题描述

我使用 swagger-ui-express package( https://github.com/scottie1984/swagger-ui-express) (Node.js) 并使用此配置正常工作:

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs',swaggerUi.serve, swaggerUi.setup(swaggerDocument));

当直接进入 /api-docs 时,一切都很好,但是当我来自 nginx 时,例如host/myApp/api-docs将我重定向到host/api-docs,很明显,重定向后我得到 404

标签: nginxswagger

解决方案


问题swagger-ui-express在于将用户重定向到 host/api-docs 并且不使用路径前缀的中间件,所以我通过在此路径中使用中间件的技巧解决了这个问题:

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/app-prefix/api-docs',swaggerUi.serve, swaggerUi.setup(swaggerDocument));

在 nginx 中我定义了两个位置:



  location /app-prefix/api-docs {
      proxy_pass http://172.18.0.89:3000/app-prefix/api-docs;
  }

  location /app-prefix/ {
      proxy_pass http://172.18.0.89:3000/;
  }


因此,当用户向 nginx 请求时,nginx 会将其路由到应用程序的第二条路径: /app-prefix/api-docs

在那个 swagger middlware 将它重定向到host/app-prefix/api-docs 并重定向到正确的路径之后,现在应用程序路由和 swagger 工作正常。


推荐阅读