[英]Node.js, assigning callback function for event 'data'
How can I assign a call back function for event 'data' and give it more then 1 standard parameter ? 如何为事件“数据”分配回调函数,并为其提供超过1个标准参数? Here is my script : 这是我的脚本:
var http = require('http');
var server = http.createServer().listen(8080);
server.on('request', onRequest);
server.on('listening', onListening);
function onRequest(request, response)
{
response.writeHead(200);
request.on('data', function(){onReqData(data,res)});
request.on('end', onReqEnd);
}
function onReqData(data, response)
{
console.log('Request : ', data.toString());
response.write('Write : ' + data.toString());
}
function listen()
{
console.log('--- / Server runs on 8080 / --- ');
}
function onReqEnd()
{
console.log(' - - - / The end of request / - - - ');
}
I don't like the syntax where the body of the callback function is in the .on() block. 我不喜欢回调函数的主体位于.on()块中的语法。
So when I'm trying to assign a callback like this : request.on('data', onReqData);
因此,当我尝试分配这样的回调时: request.on('data', onReqData);
without declaring function incoming params ( function onReqData(){...}
) I have an error which tells me that response is undefined 没有声明函数传入参数( function onReqData(){...}
),我有一个错误告诉我响应未定义
request.on('data', function(){onReqData(data,res)});
Gives me an error that data is undefined. 给我一个错误,即数据未定义。
Any help will be greatly appreciated ! 任何帮助将不胜感激 !
The 'data' event will call your function passing a chunk of data. “数据”事件将调用您的函数传递大量数据。 You need to accept chunk as a function parameter and pass it on to your onReqData function. 您需要接受块作为函数参数,并将其传递给onReqData函数。
Edit: You also need to pass the same response variable to onReqData. 编辑:您还需要将相同的响应变量传递给onReqData。
function onRequest(request, response)
{
response.writeHead(200);
request.on('data', function(chunk){onReqData(chunk, response)});
request.on('end', onReqEnd);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.