自动生成的Node.js服务器无法启动(Swagger / OpenAPI)

时间:2019-04-16 14:50:51

标签: node.js swagger openapi

我已经通过Swagger编辑器生成了一个nodejs服务器,但是当我运行“ npm start”时,服务器没有启动,并且没有返回错误。

第一次运行“ npm start”时,已经安装了所有依赖项,但是“ node index.js”没有启动服务器。

第二次尝试“ npm start”:

dev01@dev01:~/nodejs-server$ npm start

> back-end-rota-exata@1.0.0 prestart /home/dev01/nodejs-server
> npm install


> back-end-rota-exata@1.0.0 start /home/dev01/nodejs-server
> node index.js

dev01@dev01:~/nodejs-server$ 

然后我也尝试了“ node index.js”:

dev01@dev01:~/nodejs-server$ node index
dev01@dev01:~/nodejs-server$ 

什么也没发生...

这是Swagger编辑器自动生成的“ index.js”中的代码:

'use strict';

var fs = require('fs'),
    path = require('path'),
    http = require('http');

var app = require('connect')();
var oas3Tools = require('oas3-tools');
var jsyaml = require('js-yaml');
var serverPort = 8080;

// swaggerRouter configuration
var options = {
  swaggerUi: path.join(__dirname, '/swagger.json'),
  controllers: path.join(__dirname, './controllers'),
  useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);

// Initialize the Swagger middleware
oas3Tools.initializeMiddleware(swaggerDoc, function (middleware) {

  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // Validate Swagger requests
  app.use(middleware.swaggerValidator());

  // Route validated requests to appropriate controller
  app.use(middleware.swaggerRouter(options));

  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi());

  // Start the server
  http.createServer(app).listen(serverPort, function () {
    console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
    console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort);
  });

});

注意:我没有修改任何行。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我所做的是将swagger.yaml的定义从openapi: 3.0.0更改为openapi: 3.0.1,并且服务器正常工作。