Express框架


Node.js的Web開發相關的內容:

  1. Node.js不需要依賴第三方應用軟件(Apache),可以基於API自己實現
  2. 實現靜態資源服務器
  3. 路由處理
  4. 動態網站
  5. 模板引擎
  6. get和post參數傳參和處理

Web開發框架:express是基於上面的底層的API進行包裝,然后提供一套新的API,使用更加方便。

下載並安裝express:

npm install express --save

創建服務器:

//引入express模塊
const app = require('express')();
//'/'表示對根路徑的請求
app.get('/',(req,res)=>{
    res.end('ok');
}).listen(3000,()=>{
    console.log('running...');
});
//=========================================
let server = app.get('/',(req,res)=>{
    res.end('abc');
});
server.listen(3000,()=>{
    console.log('running...');
});

創建靜態資源:

/**
 * 托管靜態文件:
 * 可以指定虛擬目錄
 * 可以指定多個目錄作為靜態資源目錄
 */
const express = require('express');
const app = express();

//實現靜態資源服務
//可以訪問www目錄下的所有文件,例如http://localhost:3000/js/app.js
//use方法的第一個參數可以指定一個虛擬路徑
//必須加上這個虛擬目錄才能訪問,如:http://localhost:3000/abc/index.html
app.use('/abc',express.static('../www'));
//如果要使用多個靜態資源目錄,請多次調用 express.static 中間件函數
//let server = app.use(express.static('../www'));
app.use(express.static('../buffer'));
app.listen(3000,()=>{
    console.log('running...');
});

基本路由操作:

/**
 * 路由:根據請求路徑和請求方式進行路徑分發處理
 * http的常用請求方式:
 * post       添加
 * get        查詢
 * put        更新
 * delete     刪除
 * restful api(一種url的格式)
 */
const express = require('express');
const app = express();
//基本的路由處理
//表單只有兩種提交方式:get和post
//'/'表示對根路徑的請求
app.get('/',(req,res) => {
    res.end('get data');
});

app.post('/',(req,res) => {
    res.end('post data');
});

app.put('/',(req,res) => {
    res.end('put data');
});

app.delete('/',(req,res) => {
    res.end('delete data');
});
//=================================================
//直接使用use方法可以處理所有的路由請求
app.use((req,res)=>{
    res.send('ok');   //send的功能和end一樣
});

app.listen(3000,()=>{
    console.log('running...');
});

使用postman工具測試結果:

 使用中間件:

1.應用級中間件

/**
 * 中間件,就是處理過程中的一個環節(本質上就是一個函數)
 */
//應用級別的中間件
const express = require('express');
const app = express();
let total = 0;

//next可以將中間件彼此之間串聯起來
app.use('/user',(req,res,next) => {
    //記錄訪問時間
    console.log('Time:', Date.now())
    //next方法的作用就是把請求傳遞到下一個中間件,否則后續的中間件是沒有辦法調用的
    next()
});

app.use('/user',(req,res,next) => {
    //記錄訪問日志
    console.log('訪問了/user');
   next()
});

//最后一個中間件不需要往下傳遞
app.use('/user',(req,res) => {
    //記錄訪問次數
    total++;
    console.log(total);
    res.send('result');
});

app.listen(3000,()=>{
    console.log('running...');
});

2.路由級中間件

/**
 * 中間件的掛載方式和執行流程:
 * 1.use
 * 2.路由方式:get post put delete
 */
//路由級的中間件
const express = require('express');
const app = express();

app.get('/abc',(req,res,next) => {
    console.log(1);
    //如果不使用next,則后面的函數都無法調用,處於阻塞狀態
    //next()    //如果有next(),打印結果為:1 2  如果沒有next(),打印結果只有1,並且瀏覽器處於阻塞狀態,超時報錯
    //next()帶參數表示跳轉到下一個路由,只打印:1 3
    next('route')
},(req,res) => {
    console.log(2);
    res.send('abc');
});

app.get('/abc',(req,res) => {
    console.log(3);
    res.send('hello');
});

app.listen(3000,()=>{
    console.log('running...');
});
/**
 * 應用中間件
 */
const express = require('express');
const app = express();
//下載並安裝第三方包body-parser:npm install body-parser
const bodyParser = require('body-parser');

//掛載內置中間件
app.use(express.static(__dirname));

//處理get提交參數,get參數不需要中間件,express自己提供了處理get請求的方式
app.get('/login',(req,res) => {
    let data = req.query;
    console.log(data);
    res.send('get data');
});

//掛載參數處理中間件(post)
app.use(bodyParser.urlencoded({extended:false}));
//處理post提交參數
app.post('/login',(req,res) => {
    let data = req.body;
    //注意輸入訪問鏈接時輸入的login一定要帶后綴.html,否則訪問不了
    /* console.log(data);
    res.send('ok'); */
    if(data.username == 'admin' && data.password == '123'){
        res.send('success');
    }else{
        res.send('failure');
    }
});

app.listen(3000,()=>{
    console.log('running...');
});

對應的login.html文件:

<body>
    <form action="http://localhost:3000/login" method="get">
    用戶名:<input type="text" name="username"><br>
    密  碼:<input type="password" name="password"><br>
    <input type="submit" value="提交">
    </form>
</body>

3.錯誤處理中間件

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

4.內置中間件:就是靜態資源服務的使用

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

5.第三方中間件

使用模板引擎:

/**
 * 模板引擎整合:art-template
 */
//安裝模板引擎art-template
//npm install art-template 和 npm install express-art-template
const express = require('express');
const path = require('path');
const template = require('art-template');
const app = express();

//設置模板引擎
//1.設置模板的路徑
app.set('views',path.join(__dirname,'views'));
//2.設置模板引擎的后綴
app.set('view engine','art');
//3.使用express兼容art-template模板引擎
app.engine('art',require('express-art-template'));

app.get('/list',(req,res)=>{
    let data = {
        title : '水果',
        list : ['apple','orange','banana']
    }
    res.render('list',data);
});

app.listen(3000,()=>{
    console.log('running...');
});

對應的list.art文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>模板</title>
</head>
<body>
    <div>{{title}}</div>
    <div>
        <ul>
            {{each list}}
            <li>{{$value}}</li>
            {{/each}}
        </ul>
    </div>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM