学过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!