这是一个node.js客户端。回调函数的“响应”让我感到困惑。我把它改成了其他一些毫无意义的词,比如“哈哈”或“你好”,它仍然有效。
我隐约知道这是来自服务器的响应,但我认为服务器无法向客户端发送“响应”对象或实例。
这是什么'回应',它来自哪里?
此外,“响应”是否包含代码中的“数据”?
var http = require('http');
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
var callback = function(response){
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
}
var req = http.request(options, callback);
req.end();
这是服务器代码。
var http = require('http');
var fs = require('fs');
var url = require('url');
http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
答案 0 :(得分:1)
名字并不重要。重要的是参数的顺序和传递的内容。
在这种情况下,第一个参数是获取http.IncomingMessage
的实例,而第二个参数获取http.ServerResponse
的实例 - 请参阅:
为方便起见,可以将其称为request
和response
,但可以随意调用它们。我经常看到req
和res
。
与调用普通函数一样。所以这个:
function divide(a, b) {
return a / b;
}
与:
相同function divide(c, d) {
return c / d;
}
如果你有一个回复,它将请求作为第一个参数而响应对象作为第二个参数,那么你在内部调用它的方式并不重要。重点是其中一个对象被传递给你的第一个参数(无论它如何命名),第二个参数传递给第二个参数。
命名错误参数err
或error
:
asyncFunc(param, function (err, data) {
if (err) {
console.log('Error:', err);
} else {
console.log(data);
}
});
这与:
相同asyncFunc(param, function (error, something) {
if (error) {
console.log('Error:', error);
} else {
console.log(something);
}
});