You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js环境下OpenAPI 3.0.0与Swagger UI的basePath配置问题:接口URL缺失前缀引发403禁止访问

Fix Swagger UI Missing BasePath in Node.js with swagger-jsdoc

Looks like you're hitting a common gotcha with OpenAPI 3.x vs 2.0 syntax—basePath was replaced with the servers array in OpenAPI 3.0+, which is why adding basePath directly didn't work for you. Here's how to fix it:

Step 1: Update your Swagger Definition in index.ts

Modify the definition object in your options to include a servers array that specifies your base URL. This tells Swagger UI to prepend the base path to all your API endpoints:

const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Test API ",
      version: "1.0.0"
    },
    // Add this servers array to define your base path
    servers: [
      {
        url: "/test-api/v1",
        description: "Development environment server"
      }
    ]
  },
  apis: [`${path.join(__dirname, "/controllers/*")}`]
};

Step 2: Keep Your Controller Annotations Unchanged

You don't need to modify the path in your controller's @openapi annotations (keep it as /test). The servers configuration will automatically append the base path when Swagger UI generates the full endpoint URL.

Why Your Previous Attempts Failed

  • OpenAPI 3.x syntax change: The basePath field is an OpenAPI 2.0 feature and isn't supported in 3.0+. The servers array is the official replacement for defining base URLs in OpenAPI 3.x.
  • Controller-level annotations limitation: swagger-jsdoc pulls the root OpenAPI definition from the options.definition object, not from inline annotations in controllers. Adding basePath there won't be picked up by the generator.

Verify the Fix

Restart your server and navigate to your Swagger UI at /test-api/v1/docs. You should now see the full endpoint URL as http://api-dev/test-api/v1/test when you expand the "Test Record" endpoint, and testing it should no longer trigger the 403 forbidden error.

内容的提问来源于stack exchange,提问作者Daksh Dutta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:18:15