天天看點

Node.js學習筆記(十四、GET/POST請求)

擷取get請求資料

get請求将資料放在utl裡,是以獲得get請求資料,需要手動解析url;

執行個體:

getRequest.js:

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

console.log("服務已啟動");      

啟動,通路位址:localhost:3000/user?name=紫霞仙子&movie=《大話西遊》,url中傳遞name和movie兩個參數:

Node.js學習筆記(十四、GET/POST請求)
Node.js學習筆記(十四、GET/POST請求)

擷取 URL 的參數

可以通過url。parse來擷取url中的參數,

執行個體,urlParse.js:

var http = require('http');
var url = require('url');
var util = require('util');

http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
    // 解析 url 參數
    var params = url.parse(req.url, true).query;
    res.write("網站名:" + params.name);
    res.write("\n");
    res.write("網站 URL:" + params.url);
    res.end();
}).listen(3000);

console.log("服務已啟動");      

啟動,還是那個位址:

Node.js學習筆記(十四、GET/POST請求)
Node.js學習筆記(十四、GET/POST請求)

擷取post請求資料

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

比如上傳檔案,而很多時候并不需要理會請求體的内容,惡意的POST請求會大大消耗伺服器的資源,是以 node.js 預設是不會解析請求體的,解析post請求體,需要手動來做。

文法:

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

執行個體,postRequest.js:

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

啟動,通路:localhost:3000

Node.js學習筆記(十四、GET/POST請求)
Node.js學習筆記(十四、GET/POST請求)
Node.js學習筆記(十四、GET/POST請求)

參考:

【1】、

https://www.runoob.com/nodejs/node-js-get-post.html

繼續閱讀