I have the following js code
`var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require("path");
var io = require('socket.io')(http);
app.get('*', function (req, res){
res.sendFile(path.join(__dirname, '/Public'));
});
app.use('/home',express.static(path.join(__dirname,'/Public')));
//app.use('/static', express.static(__dirname + 'index.html'));
io.on('connection', function (socket) {
socket.on('message', function (data) {
socket.emit('news', { hello: 'world' });
});
socket.on('another-message', function (data) {
socket.emit('not-news', { hello: 'world' });
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});`
I have the HTML code
<html>
<h1>working</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000', { path :'/' +home});
socket.on('connect',function(){
socket.emit('message', 'Hello server');
});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
<body>
<p>display a message</p>
</body>
</html>`
I go to the page localhost:3000/home and i get my HTML page. But in the console i couldn't see any messages. Where am i wrong? please correct me.
Why do you say that you didn't get any errors in console? I got an error. I'll paste a screenshot of this:
Click on that to see where you've got errors.
I'll save you the time.
Change this line in index.html
var socket = io.connect('http://localhost:3000', { path :'/' +home});
to
var socket = io.connect('http://localhost:3000');
After that you'll get something like this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.