生活随笔
收集整理的這篇文章主要介紹了
node.js学习笔记(4) http服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Http是互聯網時代使用最廣泛的協議,沒有之一。
Node.js內置了http模塊,因此使用node.js搭建一個http服務非常簡單。
一、http實例
照舊,先來一個http的"Hello world!",創建http.js文件,代碼如下:
//調用http模塊
var http = require('http');var server = http.createServer();
server.on('request', function(request, response) {// 發送 HTTP 頭部// HTTP 狀態值: 200 : OK// 內容類型: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});// 發送響應數據 "Hello World !"response.end('Hello World !');
}).listen(8000);console.log('Http server is started.');
運行http.js:
lee@mypc ~/works/nodejs/study4 $ node http.js
Http server is started.
這時可以看到程序打印完"Http server is started"并沒有結束,而是一直占據進程(監聽8000端口)。
然后我們另起一個terminal,用curl測試http服務:
lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000"
Hello World !
成功打印出"Hello world !"
二、get請求
創建另一個文件http_get.js。
然后實現邏輯,接收到http請求后先判斷request.method,如果不是GET則返回404。如果是GET請求,則用url模塊獲取參數,并返回接收到的參數。
代碼如下:
//調用http模塊
var http = require('http');
//調用url模塊
var url = require('url');var server = http.createServer();
server.on('request', function(request, response) {if(request.method == 'GET') {var params = url.parse(request.url, true).query;params = JSON.stringify(params);//服務端打印參數console.log('Get params:'+params);// 發送 HTTP 頭部// HTTP 狀態值: 200 : OK// 內容類型: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});// 把請求參數返回給客戶端response.end(params+'\n');}else{response.writeHead(404, {'Content-Type': 'text/plain'});response.end('Not found !\n');}
}).listen(8000);console.log('Http server is started.');
運行http_get.js:
lee@mypc ~/works/nodejs/study4 $ node http_get.js
Http server is started.
用curl測試get得到正確結果:
lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000?id=1&name=2"
{"id":"1","name":"2"}
測試post請求則得到"Not found":
lee@mypc ~/works/nodejs/study4 $ curl -d "" "http://localhost:8000"
Not found !
三、post請求
創建一個文件http_post.js。
然后實現邏輯,接收到http請求后先判斷request.method,如果不是POST則返回404。如果是POST請求,則獲取http body,并返回接收到的內容。
代碼如下:
//調用http模塊
var http = require('http');var server = http.createServer();
server.on('request', function(request, response) {if(request.method == 'POST') {var data_post = '';request.on('data', function(data){data_post += data;});request.on('end', function(){//服務端打印參數console.log('Get body:'+data_post);// 發送 HTTP 頭部// HTTP 狀態值: 200 : OK// 內容類型: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});// 把請求參數返回給客戶端response.end(data_post+'\n');})}else{response.writeHead(404, {'Content-Type': 'text/plain'});response.end('Not found !\n');}
}).listen(8000);console.log('Http server is started.');
運行http_post.js:
lee@mypc ~/works/nodejs/study4 $ node http_post.js
Http server is started.
用curl測試post得到正確結果:
lee@mypc ~/works/nodejs/study4 $ curl -d '{"username":"lee","id":1}' "http://localhost:8000"
{"username":"lee","id":1}
測試get請求則得到"Not found":
lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000?id=1&name=2"
Not found !
總結
以上是生活随笔為你收集整理的node.js学习笔记(4) http服务的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。