落魄滑板潮牌:SHUT 衛衣 39 元清倉(立減 150 元)
阿新 • • 發佈:2021-12-20
本章節我們將為大家介紹 Node.js GET/POST請求。
獲取GET請求內容
node.js 中 url 模組中的 parse 函式提供了這個功能。
import http from 'http' import url from 'url' import util from '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);
在瀏覽器中訪問http://localhost:3000/user?name=john&url=www.baidu.com然後檢視返回結果:
獲取 URL 的引數
我們可以使用 url.parse 方法來解析 URL 中的引數,程式碼如下:
import http from 'http' import url from 'url' http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); // 解析 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);
獲取 POST 請求內容
POST 請求的內容全部的都在請求體中,http.ServerRequest 並沒有一個屬性內容為請求體,原因是等待請求體傳輸可能是一件耗時的工作,比如上傳檔案。很多時候可能並不需要理會請求體的內容,惡意的POST請求會大大消耗伺服器的資源,所以 node.js 預設是不會解析請求體,需要手動來做。
import http from 'http' 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);
以下例項表單通過 POST 提交併輸出資料:
import http from 'http' import querystring from 'querystring' let postHTML = '<html><head><meta charset="utf-8"><title>Node.js 例項</title></head>' + '<body>' + '<form method="post">' + '網站名: <input name="name"><br>' + '網站 URL: <input name="url"><br>' + '<input type="submit">' + '</form>' + '</body></html>'; http.createServer(function (req, res) { var body = ""; req.on('data', function (chunk) { body += chunk; }); req.on('end', function () { // 解析引數 body = querystring.parse(body); // 設定響應頭部資訊及編碼 res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' }); if (body.name && body.url) { // 輸出提交的資料 res.write("網站名:" + body.name); res.write("<br>"); res.write("網站 URL:" + body.url); } else { // 輸出表單 res.write(postHTML); } res.end(); }); }).listen(3000);