swagger ui showing raw html code in express nodejs

Viewed 1763

I am using swagger in nodejs express app . As expected it should have give ui in response but i am getting html code . i do not know what is wrong here. this is my swagger code

var swaggerUi = require('swagger-ui-express');
// swagger definition
var swaggerDefinition = {
  info: {
    title: 'expense manager api',
    version: '3.0.0',
    description: 'api docs for all apis',
  },
  host: 'localhost:8080',
  basePath: '/',
};
// options for the swagger docs
var options = {
  // import swaggerDefinitions
  swaggerDefinition: swaggerDefinition,
  // path to the API docs
  apis: ['./server/routes/admin_routes/*.js','./server/routes/user_routes/*.js'],// pass all in array
  };
var swaggerSpec = swaggerJSDoc(options);
app.get('/swagger.json', function(req, res) {   res.setHeader('Content-Type', 'application/json');   res.send(swaggerSpec); });
app.get('/api-docs',swaggerUi.serve,swaggerUi.setup(swaggerSpec));

but on going to localhost:8080/api-docs/ it is giving raw html code .

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Swagger UI</title>
  <link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
  <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" /><link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />

  <style>
    html
    {
        box-sizing: border-box;
        overflow: -moz-scrollbars-vertical;
        overflow-y: scroll;
    }
    *,
    *:before,
    *:after
    {
        box-sizing: inherit;
    }

    body {
      margin:0;
      background: #fafafa;
    }
  </style>
</head>

<body>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
  <defs>
    <symbol viewBox="0 0 20 20" id="unlocked">

i dont know what is wrong here .Any help would be great .Thanks in advance

2 Answers

This happens, because your express is configured to always respond with a content-type application / json. Place the Swagger configuration, before the other settings so that your express responds to the request with text / html

Use app.use() instead of app.get() as per the documentation. (enter link description here)

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

Related