我试图实现以下代码并在运行时遇到TypeError错误。
app.js
var app = module.exports = require('express').createServer();
var io = require('socket.io').listen(app);
var path = require('path');
app.listen(3000);
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.emit('welcome', {text: 'Welcome!!!'});
});
错误输出:
TypeError: Path must be a string. Received null
at assertPath (path.js:8:11)
at posix.join (path.js:479:5)
at exports.send (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/response.js:186:3)
at /Users/rluo/Desktop/learn/learnNode/socket.io_epxress/app.js:8:6
at callbacks (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:272:11)
at param (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:280:5)
at Object.Router.middleware [as handle] (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:45:10)
的package.json:
{
"name":"socketio_express-example",
"version":"0.0.1",
"private":true,
"dependencies":{
"socket.io":"0.8.7",
"express":"2.5.4"
}
}
提前致谢。
答案 0 :(得分:0)
请使用'路径'您需要的模块。试试这个:
app.get('/',function(req,res){
res.sendfile(path.join(__dirname, '/index.html'));
});
答案 1 :(得分:0)
示例:
// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
<强> __dirname
强>
添加于:v0.1.27
当前正在执行的脚本所在的目录的名称。更多详细信息https://nodejs.org/docs/latest/api/globals.html
创建套接字
var app = require('express')();
var http = require('http').Server(app);
Express将应用程序初始化为可以提供给HTTP服务器的函数处理程序(如第2行所示)。 socket.io
答案 2 :(得分:0)
在使用res.sendFile()之前,您需要设置如下的静态文件目录。
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname+'your index or static files location'));
app.get('/',function(req,res){
res.sendFile(__dirname+'index.html');
});