nginx - 在 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
解决方案
问题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 工作正常。
推荐阅读
- c++ - 如何打印数字的所有排列
- java - 如何解决 java.lang.ClassNotFoundException: DocumentException
- python - Django - 表单未更新
- python - OpenCV VideoCapture 和错误:(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
- javascript - setTimeout() 没有执行所需的功能?
- android - 如何在 Kotlin 的地图片段中获取用户的当前位置?
- javascript - 从状态中的对象反应映射项
- docker - docker ENTRYPOINT 上的多个命令
- php - 使用 MailGun API 验证电子邮件地址
- c++ - windows类型转linux