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/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// 發送響應數據 "Hello World !"
response.end('Hello World !');
}).listen(8000);
console.log('Http server is started.');
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/plain
response.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/plain
response.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}
lee@mypc ~/works/nodejs/study4 $ curl "http://localhost:8000?id=1&name=2"
Not found !
Node.js提供了一個簡單的模塊系統,可以讓node.js的文件可以相互調用。模塊是node.js應用程序的基本組成部分,文件與模塊一一對應。也就是說一個文件就是一個模塊,這些文件可以是JavaScript、json或者編譯過的c/c++文件。
- 模塊調用
有一個模塊hello.js:
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;">exports<span class="token punctuation">.</span>sayhello <span class="token operator">=</span> <span class="token keyword" style="color: rgb(102, 217, 239);">function</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">{</span>
console<span class="token punctuation">.</span><span class="token function" style="color: rgb(230, 219, 116);">log</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'Hello, '</span><span class="token operator">+</span>name <span class="token operator">+</span><span class="token string" style="color: rgb(166, 226, 46);">'.'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code>
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'./hello'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
hello<span class="token punctuation">.</span><span class="token function" style="color: rgb(230, 219, 116);">sayhello</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'James'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
運行效果如下:
<code class=" language-bash" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;">lee@mypc ~/works/nodejs/study5 $ node main.js Hello, James. </code>
另一種寫法,main2.js:
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> sayhello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'./hello'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>sayhello<span class="token punctuation">;</span>
<span class="token function" style="color: rgb(230, 219, 116);">sayhello</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'James'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
- 路徑
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'./hello'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
或<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'./hello.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'../study5/hello'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
或<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'../study5/hello.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'/home/lee/works/nodejs/study5/hello'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>
或<code class=" language-javascript" style="padding: 0px; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.5; background-color: transparent;"><span class="token keyword" style="color: rgb(102, 217, 239);">var</span> hello <span class="token operator">=</span> <span class="token function" style="color: rgb(230, 219, 116);">require</span><span class="token punctuation">(</span><span class="token string" style="color: rgb(166, 226, 46);">'/home/lee/works/nodejs/study5/hello.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code>