nodejs http網絡模塊
阿新 • • 發佈:2017-10-08
之一 tro string 程序 tails write tp服務器 get console
基本介紹
nodejs最重要的方面之一是具有非常迅速的實現HTTP和HTTPS服務器和服務的能力。http服務是相當低層次的,你可能要用到不同的模塊,如express來實現完整的Web服務器,http模塊不提供處理路由、cookie、緩存等的調用。我們主要用http模塊的地方是實現供應用程序使用的後端Web服務。
代碼部分
主要API:
http://nodejs.cn/api/http.html
例子:
// get /** * http get request * http://192.168.31.162:9001?name=001&pwd=AAAaaa */ function createGetServer() { http.createServer(function(req, res){ res.writeHead(200, {‘Content-Type‘: ‘text/plain‘}); // 解析 url 參數 console.log(req.url); var params = url.parse(req.url, true).query; res.write("url:" + req.url + "\n"); res.write("Name:" + params.name + "\n"); res.write("PWD:" + params.pwd); res.end(); }).listen(9001); } // post /** * http post request * http://192.168.31.162:9002?name=001&pwd=AAAaaa * psot:{"aaa":"001"} */ function createPostServer() { http.createServer(function (req, res) { var params = url.parse(req.url, true).query; var body = ""; req.on(‘data‘, function (chunk) { body += chunk; console.log(body); }); req.on(‘end‘, function () { // 解析參數 // body = queryString.parse(body); // 設置響應頭部信息及編碼 res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf8‘}); res.write(body); res.end(); }); }).listen(9002); }
參考:
http://nodejs.cn/api/http.html
Node.js GET/POST請求
Node.js Web 模塊
nodejs HTTP服務
node/lib/_http_server.js
node.js——http源碼解讀
淺析nodejs的http模塊
NodeJS——創建最簡單的HTTP服務器
nodejs http網絡模塊