swagger-express-middleware icon indicating copy to clipboard operation
swagger-express-middleware copied to clipboard

Using swagger-express-middleware on router do not match api base patch

Open mprokopowicz opened this issue 9 years ago • 1 comments

I have a base app (it is doing static content serving and other common tasks)

var app = express();

and a router for api mounted on /api/v2

var apiRouter = new express.Router();
app.use('/api/v2', apiRouter);

and the basePath in my swagger.json is basePath: "/api/v2"

When I'm installing swagger-express-middlerwares on the apiRouter the metadata middleware do not match any of incoming requests.

request-metada.js:33

      var basePath = util.normalizePath(context.api.basePath, router); //this resolves to "/api/v2"
      var reqPath = util.normalizePath(req.path, router); //this resolves to "/floor-plans" for a http post localhost/api/v2/floor-plans
      if (_.startsWith(reqPath, basePath)) {
        req.swagger.api = context.api;
      }

It works ok when I install swagger on the main app.

mprokopowicz avatar Mar 04 '16 12:03 mprokopowicz

I also could not get this working without some juggling of Swagger base path and how I was registering the routes in Express.

4 years too late but this is how I got it working 😄

  1. I had to strip the leading /api as that is defined by a preceeding Router. Swagger definition becomes
basePath: /v1

For me losing the /api from the Swagger definition base path isn't an issue as no clients are downloading the API Docs.

  1. Router has be to be registered without the base path but included in the route use definition`:
// Express stuff above
const APIRouter = express.Router();
rootRouter.use('/api', APIRouter);

// snip

const router = express.Router();

// Promisify Swagger Express Middleware registration
await configureSwaggerMiddleware(router, swaggerFile);

router.use('/v1/families', FamiliesRouter);
router.use('/v1/users', UsersRouter);

APIRouter.use(router);

The full url now works with metadata and parsing etc: GET /api/v1/users/123

alexb-uk avatar May 06 '20 15:05 alexb-uk