溫馨提示×

Ubuntu Swagger如何實現跨域訪問

小樊
38
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。

注意事項

  • 確保你的前端應用和后端應用在不同的端口上運行,以便測試跨域訪問。
  • 如果你需要更復雜的CORS配置(例如,只允許特定的源),可以在cors中間件中進行相應的配置:
const corsOptions = {
  origin: 'http://example.com', // 只允許來自example.com的請求
  optionsSuccessStatus: 200 // 一些舊的瀏覽器(IE11, 各種SmartTV)兼容性
};

app.use(cors(corsOptions));

通過以上步驟,你應該能夠在Ubuntu上成功配置Swagger以實現跨域訪問。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女