gpt4 book ai didi

javascript - 传递刚刚创建的参数

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:57 24 4
gpt4 key购买 nike

我正在创建一个 NodeJS/Express 监听器,并在创建 connectListener 时创建输入:

app.get('/server/:args', function(req, res) {
res.sendFile(__dirname + '/index.html');
// ...
var args = req.param("args");
var client = net.connect({port : 50505}, connectListener(args, client));
});

然后我就有了 connectListener 函数:

function connectListener(args, client) {
console.log("Connected to server.");
console.log(args);
client.write(args);
// ....
}

但是,我收到参数未定义的错误:

TypeError: Cannot read property 'write' of undefined
at connectListener (C:\Users\ES\workspace_luna\WptHash\server-src\index.js:39:8)
at C:\Users\ES\workspace_luna\WptHash\server-src\index.js:33:43
at Layer.handle [as handle_request] (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\layer.js:82:5)
at next (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\route.js:100:13)
at Route.dispatch (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\route.js:81:3)
at Layer.handle [as handle_request] (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\layer.js:82:5)
at C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:235:24
at param (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:332:14)
at param (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:348:14)
at Function.proto.process_params (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:392:3)
Error: Can't set headers after they are sent.
at SendStream.headersAlreadySent (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:313:13)
at SendStream.send (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:494:17)
at onstat (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:585:10)
at FSReqWrap.oncomplete (fs.js:99:15)

那么,如何正确创建 client 变量以便在下面的函数中使用它?我制作这样的函数 connectListener 而不是内联的原因是我计划跨更多端口复制客户端以处理同时连接,因此我不想重复使用代码,也不想使用一组全局客户端变量/数组(尽管我想我可以......)

最佳答案

看起来问题是您正在调用 connectListener ,您应该将其设置为在连接事件上调用的函数:

var client = net.connect({port : 50505}, connectListener);

如果您想使用特定参数写入特定客户端,可以通过在 connectListener 函数中定义响应来实现:

app.get('/server/:args', function (req, res) {
var client, args;

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

function connectListener () {
console.log("Connected to server.");
console.log(args);
client.write(args);
// ....
}

args = req.param("args");
client = net.connect({port : 50505}, connectListener);
});

关于javascript - 传递刚刚创建的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858896/

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