http是node自帶的模塊,經過require("http")
的方法載入;javascript
使用http建立服務器:java
http.createServer(function(request,response){ response.writeHead(200,{"Content-Type":"text/plan"}); //設置返回頭 response.write("this is test"); //返回的內容 response.end("end"); //響應結束 }).listen(2017); //設置端口
2.http.get(options[,callback]):發送請求,獲取收據,一般不發送請求數據,可用於寫爬蟲.node
options一般是個url;callback是回掉函數。服務器
http.get("http://www.baidu.com/",function(response){ response.on("data",function(data){ // do somethiing }); response.on("end",function(){ //do something }); }).on("error",function(error){ console.log(error.message); })
3.http.request(options[,callback]):發送請求,帶請求數據,可用於灌水評論,假裝請求等操做函數
hostname:請求的地址,可用於
url.parse()
方法獲得,相似於www.imooc.com
這種寫法,不帶以後的路徑;postport:端口;ui
path:以
/
開頭,一般是hostname 後面跟的路徑,例如/course/docomment
;thismethod:一般是POST;url
headers:是一個object,能夠使用事先正常請求途徑得到的response header;code
callback:回掉函數,能夠打印出請求的結構代碼res.statusCode
和JSON.stringify(res.headers)
請求頭;
最後須要將請求數據寫道請求體裏;最後收到結束請求;
var http = require("http"); var querystring = require("querystring"); var postData = querystring.stringify({ //key:value }); var options = { "hostname":"", "port":"", "path":"", "method":"", "headers":{} }; var req = http.request(options,function(res){ console.log("status:" +res.statusCode); console.log("headers:" +JSON.stringify(res.headers)); res.on("data",function(chunk){ //do something }); res.on("end",function(){ console.log("完成"); }) }); req.on("error",function(e){ console.log(e.message); }) req.write(postData); req.end();