express框架入門必須要瞭解的三個基礎知識點!

1、app.use()和app.METHOD()

兩者都有接收req的路徑,然後做出下一步 的作用。
當然,use()還有調用中間件等其他的作用,但原理還是接收路徑的原理。想詳細瞭解可看官方文檔

app.METHOD()是app.post(),app.get(),app.put()等方法的統稱

① app.use(path,callback)
② app.METHOD(path,callback)

兩者區別在於,METHOD()的回調只能使用函數,而use()還可以使用router對象等等,如下

var express = require('express');
var app = express();

var index = require('./routes/index');

app.use('/test1',function(req,res,next){
    res.send('hello test1');

});

app.get('/test2',function(req,res,next){
    res.send('hello test2');

});

app.get('/test3',index);  //報錯

app.use('/test4',index);  

app.use(express.static(__dirname + '/public')); 
//使用指定路徑的靜態文件
無論是app.use()還是app.METHOD()的path參數,都可以用正則表達式來表示,如
// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on
app.use('/ab+cd', function (req, res, next) {
  next();
})


// will match paths starting with /abc and /xyz
app.get(/\/abc|\/xyz/, function (req, res, next) {
  next();
})

更詳細請看官方文檔


2、Router()

在實際開發中通常有幾十甚至上百的路由,都寫在 index.js 既臃腫又不好維護,這時可以使用 express.Router 實現更優雅的路由解決方案。

用法如下:

    在routes文件夾中,創建路徑文件users.js

    const express = require('express')
    const router = express.Router()

    router.get('/:name', function (req, res) {
        res.send('hello, ' + req.params.name)
    })

    module.exports = router

在主文件app.js中,截取路徑並跳轉到routes文件夾users中

    const express = require('express');
    const app = express();
    const userRouter = require('./routes/users');

    app.use('/users', userRouter);

    app.listen(3000);

3、中間件

毋庸置疑,中間件這是在express框架中是最重要的東西。4.0之後的express不會再像express 3.x那樣提供一些中間件供使用。而是需要我們自己下載中間件!

中間件下載

下載中間件有兩種方法:
①使用npm install xxx -save
②將要下載的中間件添加到package.json文件中,然後npm install

中間件引用

在所需引用的js文件中,

    //比如我現在需要http模塊
    var  http = require("http");
    ...
    http.createServer(app).listen(app.get('port'), function(){
         console.log('Express server listening on port ' + app.get('port'));
    });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章