我使用swagger-ui-express软件包(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
答案 0 :(得分:2)
这是一个老问题,但我遇到了同样的问题。我可以在不使用 ngnix 重写的情况下解决这个问题。
// serve the swagger ui in a temporary directory
app.use('/temp-api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// swagger-ui-express middleware that redirect user to /api-docs will not be aware the prefix of path by ngnix
const apiDocsRedirectPath = "application/prefix/go/here".concat('/temp-api-docs/');
app.get('/api-docs', function(req, res) {
res.redirect(apiDocsRedirectPath);
});
答案 1 :(得分:1)
添加此选项并进行测试:
explorer: true,
swaggerOptions: {
validatorUrl: null
}
};
app.use('/api-docs',swaggerUi.serve, swaggerUi.setup(swaggerDocument, swaggerOption));```
答案 2 :(得分:1)
问题出在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
,然后那张夸张的中间件将其重定向到host/app-prefix/api-docs
并重定向到正确的路径,
现在应用程序路由和摇摇晃晃都可以正常工作。
答案 3 :(得分:1)
我也遇到了这个问题,标记正确的答案对我有用。但是,我不明白它是如何工作的,因为我对 Nginx 不太了解。
这是我为未来遇到此问题的人提供的解决方案。
this.app.use(
"/api-docs",
swaggerUi.serve,
swaggerUi.setup(openapiSpecification as OpenAPIV3.Document)
);
express 应用程序本身在一个 nginx 代理后面,看起来像这样
location /api/v1/myapp/ {
proxy_pass http://myapp:3001/;
}
因此,当向 example.com/api/v1/myapp/api-docs
发出请求时,它会从我的应用程序的代理发出,例如 myapp:3001/api-docs
,这很好,直到(我认为)swagger UI express 尝试从 {{1 }} 这当然是 404。
我通过将其添加为重定向来解决它。
example.com/api-docs
所以现在当 swagger 开始在 location /api/v1/myapp/ {
proxy_pass http://myapp:3001/;
}
location /api-docs/ {
return 302 /api/v1/myapp/api-docs/;
}
处请求事物时,它会被重定向到正确的位置块并且正常工作。
再说一次,不是这方面的专家,但这似乎有效,我认为它很容易理解。
需要注意的是,您只能使用一个 /api-docs,因此如果您有多个 swagger 端点,这将不起作用。