http.CreateServer()
来创建一个http.Server实例。var http = require("http");http.createServer(function (request, response){ response.writeHead(200, {"Content-Type": "text/html"}); response。write("Server start!"); response.end("Hello World ");}).listen(8080, "127.0.0.1");console.log("Server running on port 8080.");http.createServer创建了一个http.Server实例,将一个函数作为HTTP请求处理函数。这个函数接受两个参数,分别是请求对象(req)和响应对象(res)。
三. 获取GET请求内容
http.ServerRequest提供的属性没有类似于PHP语言中的$_GET或$_POST的属性,那我们该如何接受客户端的表单请求呢?由于GET请求直接被嵌入在路径中,因此可以手动解释后面的内容作为GET请求的参数。
实例:
var http = require("http");var url = require("url");var util = require("util");http.createServer(function(req, res) { res.writeHead(200, {"Content-Type": "text/html"}); res.end(util.inspect(url.parse(req.url, true)));}).listen(3000);在浏览器中访问http://127.0.0.1:3000/?name=deng&age=22,返回结果如下:
Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null,search: "?name=deng&age=22",query: { name: "deng", age: "22" }, pathname: "/",path: "/?name=deng&age=22", href: "/?name=deng&age=22" }通过url.parse,原始的path被解释为一个对象,其中query就是请求的内容。
http.createServer(function(req, res) {})
函数中的res参数传递。response.writeHead(statusCode, [headers])
:向请求的客户端发送响应头。statusCode是HTTP状态码,headers是一个表示响应头属性的对象;response.write(data, [encoding])
:向请求的客户端发送相应内容。data表示要发送的内容,encoding表示编码方式(默认是utf-8);response.end([data], [encoding])
:结束响应,告知客户端所有发送已经完成。当所有要返回的内容发送完毕的时候,该函数必须被调用一次。如果不调用该函数,客户端将永远处于等待状态。http.request(options, callback)
发起HTTP请求。var http = require("http");var querystring = require("querystring");var contents = querystring.stringify({name: "deng",age: 22});var options = {host: "dengzhr.com",method: "POST",headers: {"Content-Type": "application/x-www-form-urlencoded","Content-Length": contents.length}};var req = http.request(options, function(res) {res.setEncoding("utf8");res.on("data", function(data) {console.log(data);});});req.write(contents);req.end();在发送POST请求时,一定不要忘记通过
req.end()
结束请求,否则服务器将不会收到消息。http.get(options, callback)
是http模块的用于处理GET请求的更加简便的方法。不需要手动调用req.end()
。var http = require("http");http.get({host: "dengzhr.com"}, function(res) { res.setEncoding("utf8"); res.on("data", function(data) {console.log(data); });});总结