如何解决 swagger-ui-express 中的 CORS 问题
How to solve CORS issue in swagger-ui-express
当 运行 这个 swagger-ui-express 应用程序时,我收到 Spec2 的 "Possible cross-origin (CORS) issue?" 错误:
const express = require('express');
var cors = require('cors');
const app = express();
const swaggerUi = require('swagger-ui-express');
var options = {
explorer: true,
swaggerOptions: {
urls: [
{
url: 'http://petstore.swagger.io/v2/swagger.json',
name: 'Spec1'
},
{
url: 'http://xxx.xxx.xxx.xxx:xxxxx/swagger.json',
name: 'Spec2'
}
]
}
}
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));
app.listen(8080, () => console.log(`Listening on port 8080!`))
app.use(cors())
和 app.use(swaggerUi.cors())
都无济于事。如何修复?
检查 link,它给出了解决问题的方法。另外,如果你愿意,可以在 chrome 安装 CORS 插件并尝试。
我不确定这是否正是您面临的问题,但以下解决方案解决了我的问题。
我在端点上使用提取,错误表明收到的请求的来源 (header) 值为 null。
我已经设置了一个请求拦截器来在请求中添加一个来源 header。例子
app.get("/docs", swaggerUi.setup(null, {
swaggerOptions: {
requestInterceptor: function(request){
request.headers.Origin = `http://localhost:3000`;
return request;
},
url: `http://localhost:3000/docs/api-doc`
}
}))
当 运行 这个 swagger-ui-express 应用程序时,我收到 Spec2 的 "Possible cross-origin (CORS) issue?" 错误:
const express = require('express');
var cors = require('cors');
const app = express();
const swaggerUi = require('swagger-ui-express');
var options = {
explorer: true,
swaggerOptions: {
urls: [
{
url: 'http://petstore.swagger.io/v2/swagger.json',
name: 'Spec1'
},
{
url: 'http://xxx.xxx.xxx.xxx:xxxxx/swagger.json',
name: 'Spec2'
}
]
}
}
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));
app.listen(8080, () => console.log(`Listening on port 8080!`))
app.use(cors())
和 app.use(swaggerUi.cors())
都无济于事。如何修复?
检查 link,它给出了解决问题的方法。另外,如果你愿意,可以在 chrome 安装 CORS 插件并尝试。
我不确定这是否正是您面临的问题,但以下解决方案解决了我的问题。
我在端点上使用提取,错误表明收到的请求的来源 (header) 值为 null。
我已经设置了一个请求拦截器来在请求中添加一个来源 header。例子
app.get("/docs", swaggerUi.setup(null, {
swaggerOptions: {
requestInterceptor: function(request){
request.headers.Origin = `http://localhost:3000`;
return request;
},
url: `http://localhost:3000/docs/api-doc`
}
}))