0

我已经在 Openshift 上使用 Node、Express 4 和 MongoDB 建立了一个 REST API 的开始。我尝试了不同的配置和设置,但没有成功。现在我的主 server.js 看起来像这样:

var AppContainer = function () {
  //  Scope.
  var self = this;
  /*  ================================================================  */
  /*  Helper functions.                                                 */
  /*  ================================================================  */

  /**
   *  Set up server IP address and port # using env variables/defaults.
   */
  self.setupVariables = function () {
    //  Set the environment variables we need.
    self.ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
    self.port = process.env.OPENSHIFT_NODEJS_PORT || 3000;

  };

  /**
   *  terminator === the termination handler
   *  Terminate server on receipt of the specified signal.
   *  @param {string} sig  Signal to terminate on.
   */
  self.terminator = function (sig) {
    if (typeof sig === "string") {
      console.log('%s: Received %s - terminating sample app ...',
        Date(Date.now()), sig);
      process.exit(1);
    }
    console.log('%s: Node server stopped.', Date(Date.now()));
  };


  /**
   *  Setup termination handlers (for exit and a list of signals).
   */
  self.setupTerminationHandlers = function () {
    //  Process on exit and signals.
    process.on('exit', function () {
      self.terminator();
    });

    // Removed 'SIGPIPE' from the list - bugz 852598.
    ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
      'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
    ].forEach(function (element, index, array) {
        process.on(element, function () {
          self.terminator(element);
        });
      });
  };

  /**
   *  Initializes the sample application.
   */
  self.initialize = function () {
    self.setupVariables();
    self.setupTerminationHandlers();
  };


  self.setupServer = function () {

    /**
     * Module dependencies.
     */
    var app = require('./app');
    var http = require('http');
    /**
     * Get port from environment and store in Express.
     */
  //  var port = normalizePort(self.port);
    /**
     * Create HTTP server.
     */
    var server = http.createServer(app);
    /**
     * Listen on provided port, on all network interfaces.
     */
    server.listen(self.port, self.ipaddress, function () {
      console.log('%s: Node server started on %s:%d ...',
        Date(Date.now()), self.ipaddress, self.port);
    });
    server.on('error', onError);
    server.on('listening', onListening);



    /**
     * Event listener for HTTP server "error" event.
     */

    function onError(error) {
      if (error.syscall !== 'listen') {
        throw error;
      }

      var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

      // handle specific listen errors with friendly messages
      switch (error.code) {
        case 'EACCES':
          console.error(bind + ' requires elevated privileges');
          process.exit(1);
          break;
        case 'EADDRINUSE':
          console.error(bind + ' is already in use');
          process.exit(1);
          break;
        default:
          throw error;
      }
    }

    /**
     * Event listener for HTTP server "listening" event.
     */

    function onListening() {
      var addr = server.address();
      console.log('Server on port : ' + addr.port);
    }
  };
};


  var zapp = new AppContainer();
  zapp.initialize();
  zapp.setupServer();

我的 app.js 看起来像这样:

const http         = require('http'),
      fs           = require('fs'),
      path         = require('path'),
      contentTypes = require('./utils/content-types'),
      sysInfo      = require('./utils/sys-info'),
      env          = process.env,
      v1Route   = require('./src/resources/v1/v1Route'),
      MongoClient = require('mongodb').MongoClient;

      var express = require('express');
      var app = express();


      var connection_string = '127.0.0.1:27017/datecal';
      // if OPENSHIFT env variables are present, use the available connection info:
      if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
        connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
        process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
        process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
        process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
        process.env.OPENSHIFT_APP_NAME;
      }

      var mongoUrl = 'mongodb://' + connection_string

      MongoClient.connect(mongoUrl, function (err, db) {
        if (err) {
          console.log("Unable to connect to the mongoDB server. Error:", err);
        } else {
          //HURRAY!! We are connected. :)
          console.log("Connection established to Mongo DB with connection string " + connection_string);

          app.use('/v1', function(req, res, next){
            req.db = db;
            console.log("DB now available for all routes");
            next();
          });

          app.use('/v1', v1Route);

          // let port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
          // var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
          // app.listen(port, ipaddress, function(){
          //   console.log('Server is now listening to port ' + port + ' on ip ' + ipaddress);
          // });

        }
      });

      module.exports = app;

问题是它在我的本地环境中工作得很好,但是在 openshift 上提交和运行时,我发现服务器没有响应。OPENSHIFT_NODEJS_PORT 是 8080。现在我在 server.js 中设置我的服务器。

我还尝试使用 app.js 末尾的注释部分。我在设置中没有考虑的 openshift 环境有什么特别之处,或者我做错了什么?

4

1 回答 1

0

经过几个小时的谷歌搜索,我终于找到了解决方案。事实证明,我正在使用的负载均衡器(Haproxy)正在使用根路径,因为它是“保持活动状态”-url,而我没有提供该请求路径。我的解决方案是简单地使用“This is the API of”之类的文本字符串响应该路径上的请求。将来我可能会在根路径上有一个 API 文档。

于 2016-08-16T04:01:57.437 回答