Node.js Express框架

1.引入Express 並 建立Express框架實例css

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

app.get('/',function(req, res) {
    res.send('Hello index');
})

const server = app.listen(8081,'127.0.0.1', function () {
 
    const host = server.address().address
    const port = server.address().port
    
    console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
   
})

這裏咱們還能夠用npm 全局安裝supervisor,用於咱們啓動服務,好處就是不須要每次寫完node腳本在去命令行輸入node xxx.js來從新跑,supervisor用於熱更新,咱們每次更改完node腳本,直接在瀏覽器刷新就好。不須要從新手動跑服務html

3.請求與響應 request 和 response 對象。
request 對象表示HTTP請求,即網站對服務器進行對求情,當中包含請求查詢字符串,參數,內容,HTTp頭部等屬性
req.app:當callback爲外部文件時,用req.app訪問express的實例
req.baseUrl:獲取路由當前安裝的URL路徑
req.body / req.cookies:得到「請求主體」/ Cookies
req.fresh / req.stale:判斷請求是否還「新鮮」
req.hostname / req.ip:獲取主機名和IP地址
req.originalUrl:獲取原始請求URL
req.params:獲取路由的parameters
req.path:獲取請求路徑
req.protocol:獲取協議類型
req.query:獲取URL的查詢參數串
req.route:獲取當前匹配的路由
req.subdomains:獲取子域名
req.accepts():檢查可接受的請求的文檔類型
req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages:返回指定字符集的第一個可接受字符編碼
req.get():獲取指定的HTTP請求頭
req.is():判斷請求頭Content-Type的MIME類型
response對象:表示HTTP響應,即在接收到請求時向客服端發送的HTTP的響應數據。
res.app:同req.app同樣
res.append():追加指定HTTP頭
res.set()在res.append()後將重置以前設置的頭
res.cookie(name,value [,option]):設置Cookie
opition: domain / expires / httpOnly / maxAge / path / secure / signed
res.clearCookie():清除Cookie
res.download():傳送指定路徑的文件
res.get():返回指定的HTTP頭
res.json():傳送JSON響應
res.jsonp():傳送JSONP響應
res.location():只設置響應的Location HTTP頭,不設置狀態碼或者close response
res.redirect():設置響應的Location HTTP頭,而且設置狀態碼302
res.render(view,[locals],callback):渲染一個view,同時向callback傳遞渲染後的字符串,若是在渲染過程當中有錯誤發生next(err)將會被自動調用。callback將會被傳入一個可能發生的錯誤以及渲染後的頁面,這樣就不會自動輸出了。
res.send():傳送HTTP響應
res.sendFile(path [,options] [,fn]):傳送指定路徑的文件 -會自動根據文件extension設定Content-Type
res.set():設置HTTP頭,傳入object能夠一次設置多個頭
res.status():設置HTTP狀態碼
res.type():設置Content-Type的MIME類型
4 路由 上面已經瞭解HTTP請求的基本應用,而路由決定用哪些腳本去響應客戶端請求,
在HTTP請求中,咱們經過路由提取出請求的URL以及GET/post參數
建立express_demo.js
經過不一樣的URL來區分處理。node

const express = require('express')
const app = express()
app.use('/public', express.static('public'))
app.get('/', function(req, res) {
    console.log('主頁 GET 請求')
    res.send('Hello Get')
})
app.post('/', function(req, res) {
    console.log('主頁 POST 請求')
    res.send('Hello POST')
})

app.get('/del_user', function(req, res) {
    console.log('/del_user響應DELETE請求')
    res.send("刪除頁面")
})
app.get('/list_user', function(req, res) {
    console.log('/list_user GET 請求')
    res.send('用戶列表頁面')
})
app.get('/ab*cd', function(req, res) {
    console.log('/ab*cd GET 請求')
    res.send('正則匹配')
})
const server = app.listen('8080', '127.0.0.1', function(){
    const host = server.address().address
    const port = server.address().port
    console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
})

5 接下來是靜態文件,express提供了內置中間件express.static 來設置靜態文件。
咱們能夠建立一個public文件夾來存放img,css,js等,咱們先存放一張圖片
而後經過app.use('/public', express.static('public'))
咱們就能夠經過瀏覽器訪問127.0.0.1/piblic/images/迷笛.jpg,就能夠看到咱們存放在public的圖片了express

這是文件路徑clipboard.pngnpm

在代碼里加入json

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

clipboard.png

GET方法,咱們建立一個index.html 寫一個form 經過GET方法向指定路徑提交參數,而後經過server.js裏的process_get路由來處理輸入
1.瀏覽器

<!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>Document</title>
</head>
<body>
    <form action="http://127.0.0.1:8080/process_get" method="GET">
        First Name:<input type="text" name="first_name"><br/>
        Lase Name:<input type="text" name="last_name"><br/>
        <input type="submit">
    </form>
</body>
</html>

2.服務器

app.use('/public', express.static('public'));
app.get('/', function(req, res){
    res.sendFile(__dirname+ '/' + 'index.html')
})

app.get('/process_get',function(req, res) {
    const response = {
        'first_name': req.query.first_name,
        'last_name': req.query.last_name
    }
    console.log(response)
    res.end(JSON.stringify(response))
})

const server = app.listen('8080','127.0.0.1', function(){
    const host = server.address().address
    const port = server.address().port
    console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
})

POST方法 建立一個index.html寫一個form 經過POST方法向指定路徑提交參數,而後經過server.js裏的process_get路由來處理輸入
這裏要注意 經過post方法須要引入body-parser 用於處理 JSON, Raw, Text 和 URL 編碼的數據
1.cookie

<!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>Document</title>
</head>
<body>
    <form action="http://127.0.0.1:8080/process_get" method="POST">
        First Name:<input type="text" name="first_name"><br/>
        Lase Name:<input type="text" name="last_name"><br/>
        <input type="submit">
    </form>
</body>
</html>

2.app

const urlencodeParser = bodyParser.urlencoded({extended:false})
app.use('/public', express.static('public'));
app.get('/', function(req, res){
    res.sendFile(__dirname+ '/' + 'index.html')
})


app.post('/process_get', urlencodeParser, function(req, res) {
    const response = {
        'first_name': req.body.first_name,
        'last_name': req.body.last_name
    }
    console.log(response)
    res.end(JSON.stringify(response))
})
const server = app.listen('8080','127.0.0.1', function(){
    const host = server.address().address
    const port = server.address().port
    console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
})

Cookie 管理
咱們能夠使用中間件向 Node.js 服務器發送 cookie 信息,如下代碼輸出了客戶端發送的 cookie 信息:

const express = require('express')
const app = express()
const util = require('util')
const cookieParser = require('cookie-parser')

app.use(cookieParser())

app.get('/', function(req, res) {
    console.log('cookie:' + util.inspect(req.cookies))
})
app.listen('8080','127.0.0.1')
相關文章
相關標籤/搜索