node.js中express框架的基本使用


express是一個基於node.js平台的,快速,開放,極簡的web開發框架。

一、安裝 express

npm install express --save

  

二、簡單使用 express

//引入express
const express = require('express');
//創建一個應用
let app = express();

//匹配GET請求路徑設置回調函數
app.get('/hello', function (req, res) {
    res.end('hello');
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

通過訪問 localhost:8888/hello 我們就可以看到內容輸出了。

當然 express 還支持其他的一些請求方法,比如 app.post(),app.put(),app.delete(),app.head() 等。

//引入express
const express = require('express');
//創建一個應用
let app = express();

//匹配POST請求
app.post('/hello', function (req, res) {
    res.end('post hello');
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

如果我們想要匹配所有的請求路徑,可以使用通配符 * 號。

//引入express
const express = require('express');
//創建一個應用
let app = express();

app.get('/hello', function (req, res) {
    res.end('hello');
});

//*號匹配所有路徑
app.get('*', function (req, res) {
    res.end('not found');
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

express 還提供了 all() 方法,可以匹配所有請求方法。

//引入express
const express = require('express');
//創建一個應用
let app = express();

//匹配所有請求方法
app.all('/hello', function (req, res) {
    res.end('all hello');
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

  

三、express 中間件的概念

express中間件就是處理http請求的函數,用來完成一些特定的操作,比如登陸檢查,權限控制等等。

1、一個中間件處理完請求和響應,可以把數據傳遞給下一個中間件。

2、在回調函數中使用 next(),就可以讓請求繼續向下傳遞。

3、通過不同路徑,分別執行不同的中間件。

我們可以使用 use() ,在路由數組中添加一個中間件。注意我們設置的路由路徑最終會存放在一個數組里,由上到下的把路徑加入這個數組中。 

//引入express
const express = require('express');
//創建一個應用
let app = express();

//如果沒有設置路徑,則會匹配全部
app.use(function (req, res, next) {
    console.log('匹配全部路徑');
    //注意這里如果不調用next(),則請求並不會向下傳遞。
    next();
});

app.use('/hello', function (req, res, next) {
    console.log('use hello');
    next();
});

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

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

next() 函數可以傳入一個參數,表示錯誤信息,默認將執行錯誤中間件。

//引入express
const express = require('express');
//創建一個應用
let app = express();

app.get('/hello', function (req, res, next) {
    console.log('get hello');
    next('error!!!');
});

//注意錯誤處理中間件的參數是4個
app.use(function (err, req, res, next) {
    console.log(err);
    res.end(err);
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

  

四、express中的request對象

在express中對原生的req請求對象進行了擴展,添加了一些屬性和方法。

//引入express
const express = require('express');
//創建一個應用
let app = express();

app.get('/hello', function (req, res, next) {
    //主機名
    res.write('req.hostname : ' + req.hostname + '\r\n');
    //請求URL的路徑
    res.write('req.path : ' + req.path + '\r\n');
    //查詢字符串對象
    res.write('req.query : ' + JSON.stringify(req.query) + '\r\n');
    //請求的遠程IP地址
    res.write('req.ip : ' + req.ip + '\r\n');
    //請求方法
    res.write('req.method : ' + req.method + '\r\n');
    res.end();
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

通過 req.params 獲取路徑里的參數

//引入express
const express = require('express');
//創建一個應用
let app = express();

app.get('/list/:key/:page/:size', function (req, res, next) {
    //注意,設置了多少參數,地址就需要傳入多少參數
    res.end(JSON.stringify(req.params));
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

  

五、express中的response對象

express中也對原生的res對象進行了擴展,添加了一些屬性和方法。

const path = require('path');
//引入express
const express = require('express');
//創建一個應用
let app = express();

app.get('/send/str', function (req, res, next) {
    //send方法會自動判斷數據類型,並進行相應的head信息設置
    //如果參數是字符串,則Content-Type為 text/html
    res.send('hello, world');
});

app.get('/send/arr', function (req, res, next) {
    //如果參數是一個數組,則返回json
    res.send([1, 2, 3]);
});

app.get('/send/obj', function (req, res, next) {
    //如果參數是一個對象,則返回json
    res.send({name: 'xiaoxu', age: 24});
});

app.get('/send/number', function (req, res, next) {
    //如果是一個數字,則返回相應狀態碼短語
    res.send(404);
});

app.get('/download', function (req, res, next) {
    //提示下載文件
    res.download('./1.txt');
});

app.get('/json', function (req, res, next) {
    //響應json對象
    res.json({name: 'xiaoxu'});
});

app.get('/jsonp', function (req, res, next) {
    //客戶端請求時,需要帶上callback=test
    res.jsonp('hello');
});

app.get('/redirect', function (req, res, next) {
    //重定向到一個地址
    res.redirect('http://www.baidu.com');
});

app.get('/sendfile', function (req, res, next) {
    //發送一個文件
    res.sendFile(path.resolve('./1.txt'));
});

app.get('/sendstatus', function (req, res, next) {
    //發送一個狀態碼
    res.sendStatus(302);
});

//監聽端口
app.listen(8888, function () {
    console.log('port : 8888');
});

  

六、ejs模板的使用

支持express的模板有很多種,這里我們使用ejs作為模板引擎。

安裝ejs:

npm install ejs

使用ejs模板

const path = require('path');
const express = require('express');
//創建一個應用
let app = express();
//設置模板引擎
app.set('view engine', 'ejs');
//設置模板目錄
app.set('views', path.join(__dirname, 'views'));
//監聽
app.listen(8888);

如果我們希望,ejs能夠渲染html頁面,可以使用如下

const path = require('path');
const express = require('express');
let app = express();

//設置視圖引擎為html引擎
app.set('view engine', 'html');
//設置視圖的路徑
app.set('views', path.join(__dirname, 'views'));
//配置html引擎
app.engine('html', require('ejs').__express);

app.listen(8888);

渲染視圖,輸出內容。

const path = require('path');
const express = require('express');
let app = express();

app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express);

app.get('/hello', function (req, res, next) {
    //參數一表示模板的名稱,會在當前項目目錄下的views目錄查找
    //參數二表示傳入模板中的數據
    res.render('hello', {
        name: 'xiaoxu',
        age: 24
    });
});

app.listen(8888);

hello.html的代碼:

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <%= name %>
    <%= age %>
</body>
</html>

  

七、靜態文件服務器

有些時候我們需要在頁面上加載css,js,img等靜態資源,指定存放靜態資源的目錄,瀏覽器發出非html文件請求時,服務器會到這個目錄下找對應的資源。

const path = require('path');
const express = require('express');
let app = express();

app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express);

//注意express.static這個中間件是express內置的
app.use(express.static(path.join(__dirname, 'public')));

app.get('/hello', function (req, res, next) {
    //參數一表示模板的名稱,會在當前項目目錄下的views目錄查找
    //參數二表示傳入模板中的數據
    res.render('hello', {
        name: 'xiaoxu',
        age: 24
    });
});

app.listen(8888);

  

八、使用body-parser中間件解析post過來的數據

安裝body-parser

npm install body-parser

使用body-parser

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
let app = express();

app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express);

//解析 application/json
app.use(bodyParser.json());
//解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:false}));

app.post('/form', function (req, res) {
    console.log(req.body);
});

app.listen(8888);

  

 


免責聲明!

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



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