學過HTTP都知道。
http | MyMindNode
http需要提供request以及response信息。也就是你請求的格式以及返回信息的格式。
比如一般要求返回如下信息,那么node如何實現?
image.png
如下代碼writeHead方法返回狀態碼,文件類型等。end方法就是告訴瀏覽器,我返回完了。
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("shadou");
response.end();
}).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');
也可以這么寫.
也就是說,我們把要返回的信息包裹在了函數xx里。之后http.createServer再調用這個方法。就是所謂的函數傳遞是如何讓HTTP服務器工作的
var http = require("http");
function xx(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("doubi");
response.end();
}
http.createServer(xx).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');
總結
上述兩種方法第一個是js匿名函數,第二個是正常函數。當然啦,用匿名函數比較省字。
總之呢,就是利用js函數實現讓HTTP服務器工作,就這么easy!