我正在嘗試在我的網站http://clickthebutton.herokuapp.com上使用Express JS。當試圖安裝socket.io我得到這個錯誤:Express.js'socket.io/socket.io.js 404'
GET /socket.io/socket.io.js 404 1.911 ms - 1091
Yes, I have used 'npm install socket.io --save'
我已經看了看周圍的答案,嘗試過它們並沒有什麼幫助。如果有人認爲他們知道發生了什麼,那麼將非常感謝回覆!這裏是我的代碼:
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 io = require('socket.io')(app);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var server = app.listen(app.get('port'), function() {
console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// 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')));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.ejs
<!-- socket.io -->
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
</div>
</center>
</body>
路線/ index.js
var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
console.log(Object.keys(io.sockets.connected));
});
io.on('connection', function (socket) {
console.log('Socket.io connected!')
});
I only copy/pasted the code that referenced socket.io
謝謝!
你的設置是什麼?您提到一個公開託管的站點,然後您將顯示只偵聽localhost/127.0.0.1的代碼。此外,託管站點上的代碼還有很多對localhost:3001和port 3001的引用,當您粘貼的代碼使用端口8080時...請提供一組一致的代碼和實例。 – jcaron
@jcaron更新。 –
仍與您在託管網站上的內容不符(錯誤甚至不匹配)。 – jcaron