1. 程式人生 > >NodeJS簡易部落格系統(七)express框架入門學習

NodeJS簡易部落格系統(七)express框架入門學習

一、安裝及demo

如果已經裝好webstorm,直接新建專案如下:

否則cd到專案目錄下,使用npm install express --save即可完成安裝。

demo:

var express=require('express'); /*引入 express*/
var app=new express(); /*例項化 express 賦值給 app*/
//配置路由 匹配 URl 地址實現不同的功能
app.get('/',function(req,res){
res.send('首頁');
})
app.get('/search',function(req,res){
res.send('搜尋');
//?keyword=華為手機&enc=utf-8&suggest=1.his.0.0&wq
})
app.get('/login',function(req,res){
res.send('登入');
})
app.get('/register',function(req,res){
res.send('註冊');
})
app.listen(3000)
然後執行訪問http://localhost:3000即可看到效果。

二、路由(routing)

路由(Routing)是由一個 URI(或者叫路徑)和一個特定的 HTTP 方法(GET、 POST 等)
組成的,涉及到應用如何響應客戶端對某個網站節點的訪問。

1、簡單路由配置

GET app.get("網址",function(req,res){   });
POST app.post("網址",function(req,res){   });
PUT app.put('/user', function (req, res) {   res.send('Got a PUT request at /user'); });
DELETE app.delete('/user', function (req, res) {   res.send('Got a DELETE request at /user'); }); 

2、動態路由配置

app.get("/user/:id",function(req,res){ var id = req.params["id"]; res.send(id); }); 

3、路由的正則匹配

app.get('/ab*cd', function(req, res) {   res.send('ab*cd'); });

4、路由裡面獲取 Get 傳值 

/news?id=2&sex=nan 

app.get('/news, function(req, res) {    console.log(req.query); }); 

三、 託管靜態檔案 

1、如果你的靜態資源存放在多個目錄下面,你可以多次呼叫 express.static 中介軟體: 

app.use(express.static('public')); 

現在,public 目錄下面的檔案就可以訪問了。 

http://localhost:3000/css/style.css 
http://localhost:3000/js/app.js 
http://localhost:3000/hello.html 

2、如果你希望所有通過 express.static 訪問的檔案都存放在一個“虛擬(virtual)”目 錄(即目錄根本不存在)下面,可以通過為靜態資源目錄指定一個掛載路徑的方式來實現, 如下所示: 

app.use('/static', express.static('public'));   

現在,你就愛可以通過帶有 “/static” 字首的地址來訪問 public 目錄下 面的檔案了。 

http://localhost:3000/static/css/style.css 
http://localhost:3000/static/js/app.js 
http://localhost:3000/static/hello.html 

四、Express 中介軟體 

Express 是一個自身功能極簡,完全是由路由和中介軟體構成一個的 web 開發框架:從 本質上來說,一個 Express 應用就是在呼叫各種中介軟體。 
中介軟體(Middleware) 是一個函式,它可以訪問請求物件(request object (req)), 響應物件(response object (res)), 和 web 應用中處理請求-響應迴圈流程中的中介軟體,一般 被命名為 next 的變數。 
中介軟體的功能包括: 

  • 執行任何程式碼。
  • 修改請求和響應物件。
  • 終結請求-響應迴圈。
  • 呼叫堆疊中的下一個中介軟體。 

如果我的 get、post 回撥函式中,沒有 next 引數,那麼就匹配上第一個路由,就不會往下匹 配了。如果想往下匹配的話,那麼需要寫 next() 。

Express 應用可使用如下幾種中介軟體: 

1. 應用級中介軟體 

app.use(function(req,res,next){  /*匹配任何路由*/     //res.send('中介軟體'); 
    console.log(new Date()); 
    next();  /*表示匹配完成這個中介軟體以後程式繼續向下執行*/ 
}) 
app.get('/',function(req,res){ 
    res.send('根'); 
}) 
app.get('/index',function(req,res){ 
    res.send('首頁'); 
}) 
 

2、路由中介軟體 

app.get("/",function(req,res,next){     console.log("1");     next(); }); 
app.get("/",function(req,res){        console.log("2"); }); 

3、 錯誤處理中介軟體 

app.get('/index',function(req,res){     res.send('首頁'); }) 
/*中介軟體相應 404*/

app.use(function(req,res){    

  //res.render('404',{});

  res.status(404).render('404',{});

})

4. 內建中介軟體

//靜態服務  index.html

app.use('/static',express.static("./static"));   /*匹配所有的路徑*/ 

app.use('/news',express.static("./static"));   /*匹配所有的路徑*/ 

5. 第三方中介軟體 

body-parser 中介軟體   第三方的   獲取 post 提交的資料 
1.cnpm install body-parser --save 
 2.var bodyParser = require('body-parser') 
 3.設定中介軟體 
 //處理 form 表單的中介軟體 
 // parse application/x-www-form-urlencoded  app.use(bodyParser.urlencoded({ extended: false }));  form 表單提交的資料 
 // parse application/json  app.use(bodyParser.json());  提交的 json 資料的資料 
 4.req.body 獲取資料 

五、獲取 Get  Post 請求的引數 

● GET 請求的引數在 URL 中,在原生 Node 中,需要使用 url 模組來識別引數字串。在 Express 中,不需要使用 url 模組了。可以直接使用 req.query 物件。 
● POST 請求在 express 中不能直接獲得,可以使用 body-parser 模組。使用後,將可以用 req.body 得到引數。但是如果表單中含有檔案上傳,那麼還是需要使用 formidable 模組。 

1、安裝

npm install body-parser 

2.使用req.body 獲取 post 過來的引數 

var express = require('express')

var bodyParser = require('body-parser')  

var app = express()  

// parse application/x-www-form-urlencoded  app.use(bodyParser.urlencoded({ extended: false }))  

 // parse application/json  

app.use(bodyParser.json())  

app.use(function (req, res) {   res.setHeader('Content-Type', 'text/plain')   res.write('you posted:\n') 
res.end(JSON.stringify(req.body, null, 2)) }) 


 總結,其實小專案用到的就是路由,獲得值傳遞,響應介面,cookies儲存等等。當然,更深層次的學習還有後續。