用express在node.js开发一个socket.io聊天服务器,app.js出现的文件路径问题

终端报错:Path must be a string. Received null

clipboard.png

感觉上是 __dirname的问题,但是我改成相对路径后还是报错,求大神指导一下刚学node的小白,感激不尽~

app.js下:

var app = require('express').createServer(),
    io = require('socket.io').listen(app);

app.listen(1111);

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

});

io.sockets.on('connection',function(socket){
    socket.emit('welcome',{text:'hello world!'})
})

index.html下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>socket.io  chatting!</title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <h1>let's chatting~</h1>
    <script>
     var socket = io.connect();
     socket.on('welcome',function(data){
         console.log(data.text);
     })
    </script>
</body>
</html>
阅读 1.7k
1 个回答

res.sendfile(__dirname+'/index.html');

path 路径不要使用绝对路径,如果你想要使用绝对路径就使用options配置项的root进行配置

比如:

 var options = {
    root: __dirname + '/',
  };
res.sendFile('index.html', options);

或者直接实现相对路径

res.sendFile('/index.html');

你可以试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题