node.js之web開發(fā)框架(五)

這里所使用的的框架是express,官網(wǎng)地址:http://www.expressjs.com.cn/

安裝命令
npm i express
基本使用
//入口文件

//加載express模塊
const express = require('express');
const path = require('path');

//創(chuàng)建一個app對象,類似于創(chuàng)建一個server對象
let app = express();

//通過中間件監(jiān)聽路由請求
app.get('/index', function(req, res){
    //epress擴(kuò)展了end的方法,res.end只能返回string或者Buffer
    //send還能返回對象、數(shù)組,并且自動在頭信息加了uft8的編碼
    res.send('你好世界');
    //返回json,和send(對象)效果一樣
    // res.jsonp({name : '張三'});
    //重定向
    //res.redirect('/test');
});
//正則匹配
app.get(/^\/index(\/.+)*$/, function(req, res){
    res.send('哈哈');
});
//獲取路徑中的參數(shù)
app.get('/news/:year/:month/:day', function(req, res){
    res.send(req.params);
});

//不區(qū)分get和post,完全匹配路徑
app.all('/txt', function(req, res){
    //讀取文件并發(fā)送到客戶端
    res.sendFile(path.join(__dirname, 'public', 'test.txt'), function(err){
        if(err){
            throw err;
        }
        console.log('ok');
    });
});

//use不區(qū)分get和post,并且路徑只要以/test開頭的匹配就可以
app.use('/test', function(req, res){
    res.send('ok');
});

//處理靜態(tài)資源,如/xxx/test.html訪問的是項目下的public/test.html文件
//相同的兩個虛擬路徑注冊到了不同的文件夾,訪問靜態(tài)文件的時候會依次尋找
app.use('/xxx', express.static(path.join(__dirname, 'public')));

//啟動服務(wù)
app.listen(8888, function(){
    console.log('服務(wù)已啟動');
});
模板引擎ejs

ejs并不是express集成的,而是獨立并且兼容express,使用的要先安裝:npm i ejs

const ejs = require('ejs');
const path = require('path');

//字符模板
var html = '<h1><%=name%></h1>';
var result = ejs.render(html, {name : 'amy'});
console.info(result);

//解析文件模板
ejs.renderFile(path.join(__dirname, 'public', 'temp.html'),{name : 'kim'},function(err, data){
    console.log(data);
});
模塊化設(shè)計

啟動模塊-app.js

const express = require('express');
const router = require('./router.js');
const config = require('./config.js');

//創(chuàng)建app對象
let app = express();
//關(guān)聯(lián)路由router
//等價于app.use('/',router)
app.use(router);
//啟動服務(wù)
app.listen(config.port, function(){
    console.log('服務(wù)已啟動,端口號:'+config.port);
});

路由模塊-router.js

const express = require('express');
const handler = require('./handler.js');

//創(chuàng)建一個router對象,它既是一個對象,也是一個函數(shù)
let router = express.Router();

//掛載路由
router.get('/index', handler.index);
router.post('/add', handler.add);

//返回router對象
module.exports = router;

業(yè)務(wù)模塊-handler.js

module.exports.index = function(req, res){
    res.send('主頁');
}
module.exports.add = function(req, res){
    res.send('添加頁');
}

配置模塊-config.js

module.exports = {
    "port" : 8888
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容