2016-08-14 2 views
0

J'ai configuré le début d'une API REST avec Node, Express 4 et MongoDB sur Openshift. J'ai essayé différentes configurations et configurations sans le faire fonctionner. Maintenant, ma principale server.js ressemble à ceci:REST avec mongo, noeud et express 4 sur openshift. Ne pas répondre

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(); 

et mes app.js ressemble à ceci:

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; 

Le problème est que cela fonctionne très bien dans mon environnement local, mais au moment de commettre et le fonctionnement sur openshift je reçois que le serveur ne répond pas. Le OPENSHIFT_NODEJS_PORT est 8080. Maintenant, je configure mon serveur dans server.js.

J'ai également essayé d'utiliser la section commentée à la fin de l'app.js. Quelle est la particularité de l'environnement openshift que je ne considère pas dans ma configuration ou qu'est-ce que je fais de mal?

Répondre

0

Après plusieurs heures de googling, j'ai finalement trouvé la solution. Il s'avère que l'équilibreur de charge que j'utilise (Haproxy) utilise le chemin racine car il est "keep alive" -url et je ne servais pas ce chemin de requête. Ma solution était simplement de répondre aux demandes sur ce chemin avec une chaîne de texte comme "Ceci est l'API de". À l'avenir, j'aurai probablement un doc API sur le chemin racine.