如前壹章所述,您可以使用npm來安裝node.js模塊。具體操作請參考前面對nodejs的介紹。
Express是nodejs的壹個web開源框架,用於快速構建web項目。它主要集成了web的odejs.org/topic/50a1fcc7637ffa4155b5a264。
動詞 (verb的縮寫)請求模塊
請求模塊為開發人員訪問HTTP請求提供了壹種簡單的方法。請求還支持HTTPS的訪問方法。
安裝:
npm安裝請求
請求模塊基本涵蓋了GET、POST、HEAD、DEL等所有HTTP請求方法。但是兩個基本方法是request.get()和request.post()。
get和post的區別
獲取:
1.使用get向服務器發送和接收的請求將被附加到url。相似:?id = 1221 & amp;Name=5555在這個url中傳遞了兩個參數,壹個是id,另壹個是Name。
2.2.get請求不能超過1024字節。
帖子沒有限制,不會附加到url。
接下來,舉個簡單的例子。
獲取實例:
首先,創建新的服務器app_get.js
var http = require(" http ");
http.createServer(function(req,res){
res.writeHead(200,{ ' content-Type ':' text/plain ' });
RES . end(' Hello world \ n '+req . method);
}).聽(1337,“127 . 0 . 0 . 1”);
創建另壹個request_get.js文件來發送調解。
var request = require(' request ');
request . get(" http://127 . 0 . 0 . 1:1337 ",函數(錯誤,響應,結果){
console.log(結果);
});
在cmd中運行app_get.js,成功後打開另壹個cmd(不要關閉之前的CMD)執行request_get.js文件。
實施後的結果如下
妳好世界
得到
如您所見,通過request.get方法訪問
http://127 . 0 . 0 . 1:1337返回的結果是res.end()的參數。
發布實例:
如上,首先創建壹個新的服務器app_post.js。
var http= require("http "),
query string = require(' query string ');
http.createServer(function(req,RES){ var postData = " ";//開始異步接收客戶端post的數據。
req.addListener("data ",function (postDataChunk) {
post data+= post data chunk;
});//接收異步post數據後執行匿名回調函數。
req.addListener("end ",function(){ var postStr = JSON . stringify(query string . parse(postData));
res.writeHead(200,{ ' content-Type ':' text/plain ' });
RES . end(postStr+' \ n '+req . method);
});
}).聽(1400,“127 . 0 . 0 . 1”);
然後創建新的request_post.js
var request = require(" request ");
request . post(' http://127 . 0 . 0 . 1:1400 ',{form:{'name':'ermu ',' book':'node.js'}},function (error,response,result) {
console.log(結果);
})
如上所述,在cmd中執行後顯示的結果如下:
d:\ nodejs \ src \ request & gt;節點請求_發布. js
{"name":"ermu "," book":"node.js"}
郵政
Request POST提交了壹個json對象{"name": "ermu "," book": "node.js"},服務器隨後獲取POST數據,然後返回給客戶端,同時向客戶端響應http請求模式。
請求post參數可以通過兩種方式傳遞。
其中,第壹種是在request post中將url和form表單的數據作為json參數傳遞。例子如下:
request . post(' URL ':' http://127 . 0 . 0 . 1:1400 ',形式:{'name':'ermu ',' book':'node.js'}},函數(error,response,result) {
console.log(結果);
})
另壹種是把url和form作為兩個參數,上面的例子用的就是這種方法。
第六,?強大的模塊
本模塊的目的是解決文件上傳。
在native node.js模塊中,提供了獲取post數據的方法,但並不是直接獲取上傳的文件。