Node.js+Express構建Http服務(GET方式和POST方式)
Node.js
前提
- 環境:windows7
- 下載地址:http://nodejs.org/download/
安裝
官網下載一個安裝檔案點選下一步安裝完成即可.
驗證安裝是否成功:node -v
基本HTTP伺服器
c:/http.js
Js程式碼![收藏程式碼](http://javacrazyer.iteye.com/images/icon_star.png)
- //http是內建模組、直接引入
- var http = require('http');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'text/plain'});
-
res.end('Hello World\n'
- }).listen(8080);
- console.log('Server running on port 8080.');
執行
訪問
http://localhost:8080
小結
該例中所建立的並不是一個功能全面的HTTP伺服器,它並不能處理任何HTML檔案、圖片。事實上,無論你http://localhost:8080/後添什麼,請求後,它都將返回“Hello World”
express框架【處理GET和POST請求】
Express是對Node.js的一個高效能的封裝,是Node.js上最流行的高效能Web開發框架。
如果你用過Ruby的Sinatra.rb, 會覺得Express非常熟悉。Express作者是參考sinatra, 寫了一個基於node.js的實現。
安裝
第一步:在任意磁碟建立hello-world目錄
第二步:進入hello-world目錄執行:npm info express version 檢視express最新版本,可以看到版本號
第三步:在hello-world目錄中新建檔名為:package.json,內容如下,主要將第二步的版本號填入
Js程式碼![收藏程式碼](http://javacrazyer.iteye.com/images/icon_star.png)
- {
- "name": "hello-world",
- "description": "hello world test app",
- "version": "0.0.1",
-
"private": true
- "dependencies": {
- "express": "3.3.8"
- }
- }
package.json檔案包含了應用程式的基本資訊。其中“dependencies”部分描述了你想安裝模組的名稱和版本。該案例,接受Express 3.3.8版本,如果是3.3表示接受3.3相關的任何版本。你可以在該部分列出你想要的所有依賴。 如果你想安裝其他的依賴模組,類似安裝express一樣,可以在dependencies中定義你的模組名稱和版本,執行npm install即可安裝,一旦找到,即可安裝所列出的所有依賴。
第四步:在hello-world目錄下執行:npm install進行安裝.
一旦npm安裝依賴包完成,專案根目錄下會出現node_modules的子目錄。專案配置所需的express包都存放於這裡。
說明:第三步和第四步還有更簡單的操作方式,直接輸入命令:npm install express,會出現如下畫面直到安裝完成
第五步:nmp ls驗證express是否安裝完成
一:處理GET請求
c:/hello-world/app.js
Js程式碼![收藏程式碼](http://javacrazyer.iteye.com/images/icon_star.png)
- var express = require('express');
- var app = express();
- //接著,我們可以使用app.動詞()定義路由。
- //比如使用"GET /"響應"Hello World"字串,因為res、req都是Node提供的準確的物件,因此你可以呼叫res.pipe()
- //或req.on('data', callback)或者其它。
- //app.get('/hello.txt', function(req, res){
- // var body = 'Hello World';
- // res.setHeader('Content-Type', 'text/plain');
- // res.setHeader('Content-Length', body.length);
- // res.end(body);
- //});
- //ExpressJS框架提供了更高層的方法,比如res.send(),它可以省去諸如新增Content-Length之類的事情。如下:
- //處理GET請求
- //http://127.0.0.1:8080/hello/?name=wujintao&[email protected]
- app.get('/hello/*', function(req, res){
- console.log(req.query.name);
- console.log(req.query.email);
- res.send('Get Over');
- });
- //以上表示凡是url能夠匹配/hello/*的GET請求,伺服器都將向客戶端傳送字串“Hello World"
- //app.get('/', function(req, res){
- // res.render('index', {
- // title: 'Express'
- // });
- //});
- //上面的程式碼意思是,get請求根目錄則呼叫views資料夾中的index模板,並且傳入引數title為“Express”,這個title就可以在模板檔案中直接使用。
- //現在可以繫結和監聽埠了,呼叫app.listen()方法,接收同樣的引數,比如:
- app.listen(8080);
- console.log('Listening on port 8080');
執行
GET請求
請求:http://127.0.0.1:8080/hello/?name=wujintao&[email protected]
通過Chrome的DEV HTTP CLIENT外掛請求結果如下:
伺服器日誌資訊如下:
二:處理POST請求
c:/hello-world/app.js
![收藏程式碼](http://javacrazyer.iteye.com/images/icon_star.png)
- var express = require('express');
- var app = express();
- app.configure(function() {
- //預設情況下Express並不知道該如何處理該請求體,因此我們需要增加bodyParser中介軟體,用於分析
- //application/x-www-form-urlencoded和application/json
- //請求體,並把變數存入req.body。我們可以像下面的樣子來“使用”中介軟體[這個保證POST能取到請求引數的值]:
- app.use(express.bodyParser());
- });
- //處理POST請求
- //name和email是POST請求域中的引數名
- app.post('/hello', function(req, res) {
- console.log(req.body.name);
- console.log(req.body.email);
- res.send('Post Over');
- });
- post_mtd = function(req,res){
- res.send('我是Wujintao');
- }
- //其中這兩種形式中的function均可以定義在外部,然後引進方法名即可。其中方法post_mtd要在引用其前定義
- app.post("/wujintao",post_mtd);
- //除了app.get、app.post這種形式外,還可以採用:app.all在這裡all表示get,post等任何一種請求方式,當然也可以指定為某種特定的請求方式。
- //或者app['get']('/path', function(req,res));這種形式。
- //現在可以繫結和監聽埠了,呼叫app.listen()方法,接收同樣的引數,比如:
- app.listen(8080);
- console.log('Listening on port 8080');
執行
POST請求
請求:http://127.0.0.1:8080/hello
通過Chrome的DEV HTTP CLIENT外掛請求結果如下:
伺服器日誌資訊如下:
至此,HTTP伺服器處理GET和POST請求已經詳細講完
參考資料
http://www.nodejs.org/api/http.html#http_http_request_options_callback
http://www.nodejs.org/api/
https://github.com/visionmedia/express
http://expressjs.com/guide.html
轉載自:http://javacrazyer.iteye.com/blog/1936468