在使用 Express 的 Node app.js 之后,控制台未显示“服务器启动”

问题描述 投票:0回答:1

当我在终端上插入 Node app.js 时,控制台上没有启动服务器:3001 消息。

我的app.js文件内容:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const cors = require('cors');
var fs = require('fs');

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

var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server, {
  cors: {
    origin: "http://localhost:4200",
    methods: ["GET", "POST"]
  }
})

var user_socket_connect_list = [];

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

app.use(logger('dev'));
app.use(express.json({limit: '100'}));
app.use(express.urlencoded({ extended: true, limit: '100' }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

const corsOptions = {
  origin: "http://localhost:4200",
}

app.use(cors(corsOptions));

// import express inside dynamic add.
fs.readdirSync('./controllers').forEach((file) => {
  if(file.substr(-3) == ".js") {
    route = require('./controllers' + file);
    route.controller(app, io, user_socket_connect_list);
  }
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

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

server.listen(3001);

console.log("Server Start: 3001");

Array.prototype.swap = (x,y) => {
  var b = this[x];
  this[x] = this[y];
  this[y] = b;
  return this;
}

Array.prototype.insert = (index, item) => {
  this.splice(index,0, item);
}

Array.prototype.replace_null = (replace = '""') => {
  return JSON.parse(JSON.stringify(this).replace(/mull/g, replace));
}

String.prototype.replaceAll = (search, replacement) => {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
}

default.json 文件内容:

{
"dbConfig": {
    "host":"localhost",
    "user":"root",
    "password":"",
    "database":"online_groceries",
    "timezone":"utc+5:30",
    "charset":"utf8mb4"
}
}

login_controller和socket_controller js文件内容:

module.exports.controller = (app, io, socket_list) => {
    
}

我正在关注本教程 YouTube

如何解决?

注意:我没有 JavaScript 编程语言的经验,我将其用于 iOS 应用程序。

javascript node.js express npm
1个回答
0
投票

尝试使用回调函数,会更正确:

server.listen(3001, (err) => {
     if(err) {
          console.error('HTTP Server listen error: ' + err);
          throw err;
     }

     console.log('Server started on port: 3001');
})
© www.soinside.com 2019 - 2024. All rights reserved.