Node.js GET/POST請求

 

在很多場景中,我們的服務器都需要跟用戶的瀏覽器打交道,如表單提交。

表單提交到服務器一般都使用GET/POST請求。

本章節我們將爲大家介紹 Node.js GET/POST請求。


獲取GET請求內容

由於GET請求直接被嵌入在路徑中,URL是完整的請求路徑,包括了?後面的部分,因此你可以手動解析後面的內容作爲GET請求的參數。

node.js中url模塊中的parse函數提供了這個功能。

var http = require('http'); var url = require('url'); var util = require('util'); http.createServer(function(req, res){ res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(util.inspect(url.parse(req.url, true))); }).listen(3000);

在瀏覽器中訪問http://localhost:3000/user?name=w3c&[email protected] 然後查看返回結果:

w3cnodejs


獲取POST請求內容

POST請求的內容全部的都在請求體中,http.ServerRequest並沒有一個屬性內容爲請求體,原因是等待請求體傳輸可能是一件耗時的工作。

比如上傳文件,而很多時候我們可能並不需要理會請求體的內容,惡意的POST請求會大大消耗服務器的資源,所有node.js默認是不會解析請求體的, 當你需要的時候,需要手動來做。

var http = require('http'); var querystring = require('querystring'); var util = require('util'); http.createServer(function(req, res){ var post = ''; //定義了一個post變量,用於暫存請求體的信息 req.on('data', function(chunk){ //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中 post += chunk; }); req.on('end', function(){ //在end事件觸發後,通過querystring.parse將post解析爲真正的POST請求格式,然後向客戶端返回。 post = querystring.parse(post); res.end(util.inspect(post)); }); }).listen(3000);