ubuntu

Ubuntu Swagger如何实现跨域访问

小樊
43
2025-09-18 12:16:09
栏目: 智能运维

在Ubuntu上配置Swagger以实现跨域访问,通常涉及到修改Swagger的配置文件或代码,以允许来自不同源的请求。以下是一个基本的步骤指南:

1. 安装Swagger

首先,确保你已经在Ubuntu上安装了Swagger。你可以使用npm来安装Swagger:

sudo apt update
sudo apt install npm
sudo npm install -g swagger-ui-express

2. 创建Swagger配置文件

创建一个Swagger配置文件,例如swagger.json,并定义你的API规范。

{
  "swagger": "2.0",
  "info": {
    "title": "Example API",
    "version": "1.0.0"
  },
  "host": "localhost:3000",
  "basePath": "/api",
  "schemes": [
    "http"
  ],
  "paths": {
    "/items": {
      "get": {
        "summary": "Find an item",
        "responses": {
          "200": {
            "description": "An array of items"
          }
        }
      }
    }
  }
}

3. 创建Express应用并集成Swagger

创建一个Express应用,并将Swagger UI集成到其中。

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();
const swaggerDocument = YAML.load('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/items', (req, res) => {
  res.json([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

4. 配置跨域访问

为了允许跨域访问,你需要使用cors中间件。

首先,安装cors

sudo npm install cors

然后,在Express应用中使用cors中间件:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const cors = require('cors');

const app = express();
const swaggerDocument = YAML.load('./swagger.json');

app.use(cors()); // 启用CORS

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/items', (req, res) => {
  res.json([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

5. 测试跨域访问

启动你的Express应用:

node app.js

然后,在浏览器中访问http://localhost:3000/api-docs,你应该能够看到Swagger UI界面,并且能够从不同的源访问你的API。

注意事项

const corsOptions = {
  origin: 'http://example.com', // 只允许来自example.com的请求
  optionsSuccessStatus: 200 // 一些旧的浏览器(IE11, 各种SmartTV)兼容性
};

app.use(cors(corsOptions));

通过以上步骤,你应该能够在Ubuntu上成功配置Swagger以实现跨域访问。

0
看了该问题的人还看了