gpt4 book ai didi

node.js - Nodejs : Path must be a string. 收到空

转载 作者:搜寻专家 更新时间:2023-10-31 23:59:27 24 4
gpt4 key购买 nike

我试图实现以下代码,但在运行时遇到了 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"
}
}

提前致谢。

最佳答案

  • 错误很明显,你需要指定一个绝对(而不是相对)路径

例子:

//假设 index.html 与该脚本位于同一目录中

res.sendFile(__dirname + '/index.html');
  • 你根本不需要路径全局对象

__目录名添加于:v0.1.27

当前正在执行的脚本所在的目录的名称。有关更多详细信息 https://nodejs.org/docs/latest/api/globals.html

  • 检查此线程 TypeError: Path must be a string

  • 创建套接字

    var app = require('express')();

    var http = require('http').Server(app);

    Express 将应用程序初始化为一个函数处理程序,您可以将其提供给 HTTP 服务器(如第 2 行所示)。 socket.io

__dirname vs path

关于node.js - Nodejs : Path must be a string. 收到空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41032412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com