這是一個node.js客戶端。回調函數的'響應'使我感到困惑。我把它變成了一些其他無意義的詞,如'哈哈'或'你好',它仍然有效。這些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/');
難道[我的文章](https://stackoverflow.com/問題/ 41345353/whats-the-response-argument-in-these-node-js-code/41345470#41345470)回答你的問題?如果是這樣,那麼你可以考慮[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235),以便其他人搜索這個主題可以看到它有一個可接受的答案。 – rsp