Node.js环境下OpenAPI 3.0.0与Swagger UI的basePath配置问题:接口URL缺失前缀引发403禁止访问
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
basePathfield is an OpenAPI 2.0 feature and isn't supported in 3.0+. Theserversarray 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.definitionobject, not from inline annotations in controllers. AddingbasePaththere 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

