示例代碼請訪問我的GitHub: github.com/chencl1986/…
同時處理GET/POST請求
通常在開發過程中,同一臺服務器需要接收多種類型的請求,并區分不同接口,向客戶端返回數據。
最常用的方式,就是對請求的方法、url進行區分判斷,獲取到每個請求的數據后,統一由一個回調函數進行處理。
如下示例代碼,可以在/lesson08/form_get.html和/lesson08/form_post.html中,通過提交表單查看效果。
示例代碼:/lesson08/server.js
const http = require('http')
const url = require('url')
const querystring = require('querystring')const server = http.createServer((req, res) => {// 定義公共變量,存儲請求方法、路徑、數據const method = req.methodlet path = ''let get = {}let post = {}// 判斷請求方法為GET還是POST,區分處理數據if (method === 'GET') {// 使用url.parse解析get數據const { pathname, query } = url.parse(req.url, true)path = pathnameget = querycomplete()} else if (method === 'POST') {path = req.urllet arr = []req.on('data', (buffer) => {// 獲取POST請求的Buffer數據arr.push(buffer)})req.on('end', () => {// 將Buffer數據合并let buffer = Buffer.concat(arr)// 處理接收到的POST數據post = querystring.parse(buffer.toString())complete()})}// 在回調函數中統一處理解析后的數據function complete() {console.log(method, path, get, post)}
})server.listen(8080)
復制代碼