Node.js 代码正确,但在节点js套接字io上显示错误?
代码正确,但在节点js套接字io上显示错误 徖 app.jsNode.js 代码正确,但在节点js套接字io上显示错误?,node.js,Node.js,代码正确,但在节点js套接字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', functi
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>
返回值
start server on port :3000
express deprecated res.sendfile: Use res.sendFile instead app.js:6:6
将问题中的命令转化为答案 Express正在取消对
res.sendfile
的访问,以支持res.sendfile
sendFile
需要文件的完整路径
假设index.html
与app.js
位于同一文件夹中,您可以使用:
const path = require('path');
res.sendFile(path.join(__dirname, 'index.html'))
如果您在将来移动文件,请简单调整
path.join
express弃用的res.sendfile:使用res.sendfile代替app.js:6:6阅读此解决方案,当我更改为res.sendfile('index.html')时,它是sendfile
而不是sendfile
代码>----显示错误----TypeError:path必须是绝对的,或者在ServerResponse.sendFile(/home/admin/web/my domain.com/public\u html/node\u modules/express/lib/response.js:421:11)的/home/admin/web/my domain.com/public\u html/app.js:6:6 at Layer.handle[作为handle\u请求](/home/admin/web/my domain.com/public_html/node_modules/express/lib/router/layer.js:95:5)下一步(/home/admin/web/my domain.com/public_html/node_modules/express/lib/router/route.js:137:13)在route.dispatch(/home/admin/web/web/my domain.com/public_html/node_modules/express/lib/router/route.js:112:3)
index.html文件位于哪里?我想……您需要更改文件路径res.sendFile(“to located path”);
const path = require('path');
res.sendFile(path.join(__dirname, 'index.html'))