node.js - Node 应用程序在本地主机上运行,​​而不是在服务器上运行(Digitalocean、express.js)

标签 node.js ubuntu express deployment digital-ocean

这是我尝试部署的第一个应用程序,但我碰壁了,失去了最后一根头发。

我正在关注本教程: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04

当我使用教程中的 hello.js 应用程序构建它时,一切正常。当我尝试将他们的应用程序切换为我构建的应用程序时,它不起作用。我的应用程序在我的本地主机上运行良好。

这是我用来创建服务器的代码,我觉得这就是问题发生的地方。

bin/www

#!/usr/bin/env node

var app = require('../app');
var debug = require('debug')('delivbeer:server');
var http = require('http');


var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.createServer(app);

server.listen(port, '127.0.0.1');
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

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;
  }
}

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// // var index = require('./routes/index');
// var users = require('./routes/users');

//Setup Mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/delivbeer', {
  useMongoClient: true,
  /* other options */
});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//Setup Express Session / Passport 
var passport = require('passport');
var expressSession = require('express-session');

app.use(expressSession({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

var initPassport = require('./passport/init');
initPassport(passport);

//Setup Connect-Flash
var flash = require('connect-flash');
app.use(flash());

//Routes
var routes = require('./routes/index')(passport);
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

当我运行时,我没有收到任何错误,但如果当应用程序在服务器上运行时我curl http://127.0.0.1:3000,我会收到连接拒绝错误。

请帮忙!

最佳答案

我看到的主要问题是 Digital Ocean 教程使用内置 Node http 模块,而您尝试在 Express 之外使用该模块用于处理网络服务器的库。

请注意本教程中的 hello.js 是:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080, 'APP_PRIVATE_IP_ADDRESS');
console.log('Server running at http://APP_PRIVATE_IP_ADDRESS:8080/');

传递给 createServer 函数的参数是另一个带有参数 reqres 的函数。

在您的 bin/www 代码中,您有 var server = http.createServer(app);

但是您传递给 createServerapp 是从 app.js 导出的任何内容 - 不是函数,而是完整的 Express 对象(var app = express(); ... module.exports = app;)

我建议遵循 Express guide 。从那里的例子:

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

您可以在 bin/www 中执行类似的操作。实际上,看起来这一切都可以在您的 app.js 文件中完成。您可以包含:

,而不是在最后执行 module.exports
var port = normalizePort(process.env.PORT || '3000');
app.listen(port, function() {
  console.log(`App running on port ${port}`);
}

// copy over normalizePort function from bin/www

然后要启动服务器,只需从该目录运行 node app.js 即可。

关于node.js - Node 应用程序在本地主机上运行,​​而不是在服务器上运行(Digitalocean、express.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260429/

相关文章:

node.js - `fs-extra` 与 `bluebird ` 集成得到 `Cannot read property ' 然后 ' of undefined` 错误

javascript - Node.js Promise 只返回预期内容的一小部分

node.js - 如何使用 upworks api 创建里程碑,其 api 中定义的里程碑会出现授权错误

ubuntu - 无法在 ubuntu 21.10 中安装 pgAdmin 4

javascript - 如何在 Express.js 中处理 ETIMEDOUT

javascript - 使用回调函数进行快速路由时未定义参数

linux - NEO4J : ERROR: Unable to find java. (无法执行/usr/lib/jvm/java-7-oracle/jre/bin/java/bin/java)

ubuntu - vlc 播放器无法播放 m3u8 播放列表

javascript - 如何在表单提交时获取html组件值?

json - 当数据只是字符串时 Expressjs 无效 JSON