我们目前正在尝试构建一个与express-generator一起使用的nodejs应用程序。我目前正在尝试将Primus websocket添加到我的应用程序中。问题是,如果我不将app.listen(port)添加到我的app.js文件中,我的应用程序将不会显示在localhost:3000上,即使它包含在bin / www文件中。如果我添加app.listen(端口),我的应用程序似乎无法找到primus库,尽管我将它安装到我的依赖项中。我不知道我的应用程序找不到primus库的问题是否与我是否添加app.listen(端口)这一事实有关。
我的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"
}
}
我的bin / 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);
}
答案 0 :(得分:0)
尝试这段代码。显示Primus接受WS连接,而Express app字段请求特定路由。我们的服务器对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' }
答案 1 :(得分:-1)
我自己解决了这个问题,这是一个愚蠢的问题。 解决方案是命令nodemon bin / www&#39;而不是'nodemon app.js&#39;