代码正确,但在节点 js 套接字 io 上显示错误?



代码正确,但在节点js套接字io上显示错误?

.......

应用.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');
});

索引.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>

.

安全信息

node app.js

返回值

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

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

快递正在贬低res.sendfile,有利于res.sendFile.

sendFile需要文件的完整路径。

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

const path = require('path');
res.sendFile(path.join(__dirname, 'index.html'))

如果您将来移动文件,则只需调整path.join

最新更新