代码是正确的但在节点js socket io上显示错误?

时间:2018-05-01 06:51:53

标签: node.js

代码是否正确,但在节点js socket io上显示错误?

............................................... .................................................. ...................

app.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req,res){
    res.sendfile('index.html');
});

var clients = 0;
io.on('connect', function(socket){
    clients++;
    io.sockets.emit('boardcast', {message: clients + ' clients connected!'});

//console.log(io.sockets)

    socket.on('disconnect', function(){
        clients--;
        io.sockets.emit('boardcast', {message: clients + ' clients connected!'});
    });
});

http.listen(3000, function(){
    console.log('start server on port :3000');
});

的index.html

<html>
<head></head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>

<script type="text/javascript">
var socket = io();
socket.on('boardcast', function(data){
    document.body.innerHTML = '';
    document.write(data.message);
});
</script>

<h1>hello world</h1>
</body>
</html>

SSH

node app.js

返回值

start server on port :3000
express deprecated res.sendfile: Use res.sendFile instead app.js:6:6

1 个答案:

答案 0 :(得分:1)

将问题中的命令放入答案中。

Express正在res.sendfile取消res.sendFile

sendFile需要文件的完整路径。

假设index.htmlapp.js位于同一文件夹中,您可以使用:

const path = require('path');

res.sendFile(path.join(__dirname, 'index.html'))

如果您在将来简单调整path.join

中移动文件