gpt4 book ai didi

javascript - Node hapi 应用程序启动,但似乎未绑定(bind)到端口

转载 作者:行者123 更新时间:2023-12-01 03:15:02 25 4
gpt4 key购买 nike

我有一个正在开发的 hapi 应用程序。在使用 Procfile 运行我常用的 node-foreman 时,应用程序在命令行中加载,没有错误,但在浏览到配置的端口时,页面错误,没有连接,或者具体来说,连接被拒绝。返回 CLI,没有错误。来自 server.start 的简单消息“服务器运行于http://localhost:3000

我尝试直接使用 gulp 启动(没有错误)。没有浏览器访问权限。

我尝试直接使用 Node 启动(没有错误)。没有浏览器访问权限。

我尝试使用 hapi 和express 创建一个 hello world 应用程序,两者都没有错误并且确实在浏览器中加载。

我什至将代码版本控制回我知道有效的版本。从 CLI 可以正常启动服务器,但无法加载/访问浏览器。

我有点卡住了,希望有任何想法,甚至是解决问题的路径。

提前谢谢您。

这是应用程序 JS:

var config = require('./config');
hapi = require('../lib/hapi'),
chalk = require('chalk'),

module.exports.init = function (callback) {
//init app bserver
server = hapi.init();

callback(server, config );
};

module.exports.start = function (callback) {
var _this = this;

_this.init(function (server, config) {

// Start the app by listening on <port>
server.start(function () {


// Logging initialization
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| ' + config.app.title+ '\t\t\t|'));
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| Environment:\t' + process.env.NODE_ENV));
console.log(chalk.green('| Standard Port:\t' + config.port));
if (config.https.ssl === true ) {
console.log(chalk.green('| Secure Port:\t' + config.https.port));
console.log(chalk.green('| HTTPs:\t\ton'));
}
console.log(chalk.green('| App version:\t' + config.version));
console.log(chalk.green('| App url:\t\t' + ((config.https.ssl === true ? 'https' : 'http')+"://"+config.url)));
console.log('+-----------------------------------------------------------+');
console.log('| Database Configuration\t\t\t\t\t|');
console.log('+-----------------------------------------------------------+');
console.log(chalk.green(JSON.stringify(config.db, null, 4)));
console.log('+-----------------------------------------------------------+');

if (callback) callback(server, db, config);
});

return server;
});

};

这是 HAPI 包括:

var config = require('../general/config'),
Hapi = require('hapi'),
Good = require('good'),
Hoek = require('hoek'),
Inert = require('inert'),
Vision = require('vision'),
Path = require('path'),
Boom = require('boom'),
Bell = require('bell'),
Cookie = require('hapi-auth-cookie'),
Url = require('url'),
hapiAuthSessions = require('./sessions'),
Promise = require('bluebird'),
fs = require('fs');


/* Initialize ORM and all models */
module.exports.initDBConnections = function( server ) {
server.register([
{
register: require('hapi-sequelize'),
options: [
{
sequelize: new Sequelize(process.env.DATABASE_URL),
name: config.db.connection.database,
models: config.files.server.models,
sync: true,
forceSync:false
}
]
}
], function(err) {

Hoek.assert(!err, err);

});
}

/**
* Initialize rendering engine
*/
module.exports.initRenderingEngine = function (server) {

var paths = [];
var layouts = [];
var partials = [];
var helpers = [];

/* add each module paths to rendering search, assume if route, there is a view fr module */
config.files.server.routes.forEach(function (routePath) {
var rp = Path.relative(Path.join(__dirname,'../../'),Path.resolve(Path.dirname(routePath)+'/../../'))
if(fs.existsSync(rp+'/server/views/'+config.theme+'/content'))
paths.push(rp+'/server/views/'+config.theme+'/content');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/errors'))
paths.push(rp+'/server/views/'+config.theme+'/errors');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/layouts'))
layouts.push(rp+'/server/views/'+config.theme+'/layouts');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/partials'))
partials.push(rp+'/server/views/'+config.theme+'/partials');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/helpers'))
helpers.push(rp+'/server/views/'+config.theme+'/helpers');
});

server.views({
engines: {
html: require('handlebars')
},
path: paths,
layoutPath: layouts,
partialsPath: partials,
helpersPath: helpers,
layout: 'base.view'
});
}


/**
* Initialize local variables
*/
module.exports.initLocalVariables = function (server) {
// Setting application local variables
for (var property in config) {
if (config.hasOwnProperty(property)) {
if (!server.app[property]) {
server.app[property] = config.app[property]
}
}
}
};



/**
* Initialize static routes for browser assets
*/
module.exports.initStaticRoutes = function (server) {

server.route([{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../public'),
redirectToSlash: true,
listing: false,
defaultExtension: 'html'
}
}
},{
method: 'GET',
path: '/assets/vendor/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../node_modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'js'
}
}
}]);
}


/**
* Initialize server logging
*/
module.exports.initLogging = function (server) {
return {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }]
}, {
module: 'good-console'
}, 'stdout']
}
};
}

/**
* Initialize App Tenant
*/

module.exports.initAppTenant = function (server) {
server.ext('onRequest', function (req, res) {
server.app['tenant'] = req.info.hostname;
res.continue();
});

};

/**
* Initialize ensure SSL
*/
module.exports.initSSL = function(server) {
server.select('http').route({
method: '*',
path: '/{p*}',
handler: function (req, res) {

// redirect all http traffic to https
console.log('redirecting',config.url + req.url.path);
return res.redirect('https://' + config.url + req.url.path).code(301);
},
config: {
description: 'Http catch route. Will redirect every http call to https'
}
});
}

/**
* Initialize static routes for modules in development mode browser assets
*/
module.exports.initModulesStaticRoutes = function(server) {

if (process.env.NODE_ENV === 'development') {
server.route({
method: 'GET',
path: '/modules/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'html'
}
}
});
}
}

/**
* Configure the modules server routes
*/
module.exports.initModulesServerConfigs = function (server) {
config.files.server.configs.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};

/**
* Configure the modules server routes
*/
module.exports.initModulesServerRoutes = function (server) {
config.files.server.routes.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};

/**
* Configure Socket.io
*/
module.exports.configureSocketIO = function (server) {
// Load the Socket.io configuration
var server = require('./socket.io')(server);

// Return server object
return server;
};

/**
* Initialize hapi
*/
module.exports.init = function init() {

var server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
},
state: {
isSameSite: 'Lax'
}
},
debug: {
'request': ['error', 'uncaught','all','request']
},

cache: [
{
name: 'cacheMem',
engine: require('catbox-memcached'),
host: '127.0.0.1',
port: '8000',
partition: 'cache'
},{
name : 'cacheDisk',
engine : require('catbox-disk'),
cachePath: '/var/tmp',
partition : 'cache'
}
]
});

server.connection({
labels: 'http',
port: config.port
});

if(config.https.ssl == true) {
server.connection({
labels: 'https',
port: config.https.port,
tls: {
key: config.https.key,
cert: config.https.cert
}
});

/* redirect ssl */
this.initSSL(server);
}

server.register([Vision,{register: Good, options: this.initLogging(server)},Cookie,Bell,Inert], function(err) {

Hoek.assert(!err, err);

var _this = module.exports;
var _thisServer = server.select((config.https.ssl == true ? 'https' : 'http'));

/* Initialize sessions */
hapiAuthSessions._init(_thisServer);

/* detect app tenant */
_this.initAppTenant(_thisServer);


/* app local variables */
_this.initLocalVariables(_thisServer);

/* logging */
_this.initLogging(_thisServer);

/* static file serving */
_this.initStaticRoutes(_thisServer);

/* module config, routes, static routes */
_this.initModulesStaticRoutes(_thisServer);
_this.initModulesServerConfigs(_thisServer);
_this.initModulesServerRoutes(_thisServer);


/* rendering engine */
_this.initRenderingEngine(_thisServer);

// Configure Socket.io
server = _this.configureSocketIO(_thisServer);


//server.start located in ../general/app.js

});
return server;
}

这是 CLI 输出:

[13:58:31] [nodemon] starting `node --inspect server.js`
[13:58:31] [nodemon] child pid: 5596
Debugger listening on ws://127.0.0.1:9229/e2f5837f-b552-4156-b004-e7adb3d30d05
For help see https://nodejs.org/en/docs/inspector
+-----------------------------------------------------------+
| APP - Development Environment |
+-----------------------------------------------------------+
| Environment: development
| Standard Port: 3000
| Secure Port: 3001
| HTTPs: on
| App version: 0.3.0
| App url: https://localhost:3001
+-----------------------------------------------------------+
| Database Configuration |
+-----------------------------------------------------------+
{
"client": "postgresql",
"connection": {
"host": "localhost",
"port": "5432",
"database": "database",
"user": "user",
"password": "password",
"ssl": true
},
"pool": {
"min": 2,
"max": 10
},
"migrations": {
"tableName": "knex_migrations"
},
"debug": true
}
+-----------------------------------------------------------+

最佳答案

好的。我找到了答案(这是一周两次的小细节——真丢脸)。

导致我遇到更大问题的较小问题是在 server.start(callback) 上,我没有进行任何错误检查,类似于:

server.start(function(err) {
if(err) {
throw err;
}
});

一旦我添加了错误日志记录,它就暴露了服务器悄然失败的原因。

我的 Hapi 配置需要 memcached 模块,但我尚未在本地启动我的 memcached 服务器。

一切都回到按设计工作:)

关于javascript - Node hapi 应用程序启动,但似乎未绑定(bind)到端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45597472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com