鍍金池/ 問(wèn)答/網(wǎng)絡(luò)安全  HTML/ 用express在node.js開(kāi)發(fā)一個(gè)socket.io聊天服務(wù)器,app.j

用express在node.js開(kāi)發(fā)一個(gè)socket.io聊天服務(wù)器,app.js出現(xiàn)的文件路徑問(wèn)題

終端報(bào)錯(cuò):Path must be a string. Received null

clipboard.png

感覺(jué)上是 __dirname的問(wèn)題,但是我改成相對(duì)路徑后還是報(bào)錯(cuò),求大神指導(dǎo)一下剛學(xué)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>
回答
編輯回答
命多硬

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

path 路徑不要使用絕對(duì)路徑,如果你想要使用絕對(duì)路徑就使用options配置項(xiàng)的root進(jìn)行配置

比如:

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

或者直接實(shí)現(xiàn)相對(duì)路徑

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

你可以試試

2017年7月10日 00:18