带有 express-generator 的 Nodejs 应用程序,并尝试添加 primus websocket
Posted
技术标签:
【中文标题】带有 express-generator 的 Nodejs 应用程序,并尝试添加 primus websocket【英文标题】:Nodejs application with express-generator, and trying to add primus websocket 【发布时间】:2017-10-03 01:16:38 【问题描述】:我们目前正在尝试构建一个与 express-generator 一起使用的 nodejs 应用程序。我目前正在尝试将 Primus websocket 添加到我的应用程序中。问题是如果我不将 app.listen(port) 添加到我的 app.js 文件中,我的应用程序将不会显示在 localhost:3000 上,即使它包含在 bin/www 文件中。如果我添加 app.listen(port),我的应用程序似乎无法找到 primus 库,尽管我将它安装到我的依赖项中。不知道我的app找不到primus库的问题是不是和我有没有添加app.listen(port)有关。
我的 app.js 文件 [
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/facebookusers');
var http = require("http");
var Primus = require("primus");
var options =
transformer: "engine.io"
var facebook = require('./routes/facebook');
var users = require('./routes/users');
var profile = require('./routes/profile');
var login = require('./routes/login');
var admin = require('./routes/admin');
var vote_now = require('./routes/vote_now');
var vote_result = require('./routes/vote_result');
var groups = require('./routes/groups');
var endvoting = require('./routes/endvoting');
var roles = require('./routes/roles');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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')));
app.use(require('morgan')('combined'));
app.use(session( secret: 'marioWim' ));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/users', users);
app.use('/profile/', profile);
app.use('/login', login);
app.use('/admin/', admin);
app.use('/vote_now', vote_now);
app.use('/vote_result', vote_result);
app.use('/auth/facebook', facebook);
app.use('/groups', groups);
app.use('/endvoting', endvoting);
app.use('/roles',roles);
// 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');
);
app.listen(3000);
module.exports = app;
我的 package.json 文件
"name": "demo-or-die",
"version": "0.0.0",
"private": true,
"scripts":
"start": "node ./bin/www"
,
"dependencies":
"body-parser": "^1.17.1",
"connect-ensure-login": "^0.1.1",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.3",
"debug": "~2.6.3",
"engine.io": "^3.1.0",
"express": "~4.15.2",
"express-session": "^1.15.2",
"flash": "^1.1.0",
"jade": "~1.11.0",
"mongoose": "^4.9.6",
"morgan": "^1.8.1",
"named-routes": "^2.0.6",
"passport": "^0.3.2",
"passport-facebook": "^2.1.1",
"primus": "^7.0.1",
"prompt": "^1.0.0",
"pug": "^2.0.0-beta.12",
"serve-favicon": "~2.4.2"
,
"devDependencies":
"gulp": "^3.9.1",
"gulp-changed": "^3.0.0",
"gulp-imagemin": "^3.2.0",
"gulp-nodemon": "^2.2.1",
"gulp-sass": "^3.1.0"
我的垃圾桶/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('demo-or-die:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val)
var port = parseInt(val, 10);
if (isNaN(port))
// named pipe
return val;
if (port >= 0)
// port number
return port;
return false;
/**
* 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();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
【问题讨论】:
【参考方案1】:试试这段代码。显示 Primus 接受 WS 连接,而 Express 应用程序字段请求特定路由。我们的服务器是 Express 和 Primus 通用的。
var Express = require('express');
var app = Express();
var server = require('http').createServer(app);
var Primus = require('primus');
var primus = new Primus(server, transformer: 'sockjs', pathname:'ws');
primus.on('initialised', function()
console.log('Primus Initialized!');
);
primus.on('connection', function connection(spark)
console.log("spark connected");
spark.write("Hello Client, I'm the Server");
spark.on('data', function(data)
console.log('data:', data);
spark.write('received.');
);
);
app.get('/', function(req, res)
res.send('home');
);
app.get('/test', function(req, res)
res.send('test');
);
server.listen(host: '0.0.0.0', port: 8081);
wscat
节点包在测试时很有用:
客户
$ curl 127.0.0.1:8081/test
test
$ wscat -c 127.0.0.1:8081/ws/websocket
connected (press CTRL+C to quit)
< "Hello Client, I'm the Server"
> "foo": "bar"
< "received."
服务器
$ node test.js
Primus Initialized!
spark connected
data: foo: 'bar'
【讨论】:
【参考方案2】:我自己解决了这个问题,这是一个愚蠢的问题。 解决方案是命令“nodemon bin/www”而不是“nodemon app.js”
【讨论】:
以上是关于带有 express-generator 的 Nodejs 应用程序,并尝试添加 primus websocket的主要内容,如果未能解决你的问题,请参考以下文章
在 express-generator 中使用 bin 文件而不是 .js 的好处