快速上手Node.JS中的express

Express

安裝

基於 Node.js 平臺,快速、開放、極簡的 Web 開發框架

基本使用

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log(`Example app listening on port 3000!`))

基本路由

路由器

  • 請求方法
  • 請求路徑
  • 請求處理函數

get:

// 當以 GET 方法請求 / 的時候,執行對應的處理函數
app.get('/', (req, res) => res.send('Hello World! GET'))

post:

app.post('/', (req, res) => res.send('Hello World! POST'))

在Express中獲取表單GET數據請求體

Express內置了一個API,可以直接通過req.query來獲取

app.post('/sub',function(req, res){
    var comment = req.query
    comment.dateTime = time.format(new Date(), 'YY-MM-DD')
    comments.push(comment)
    // 重定向
    res.redirect('/')
})

在Express中獲取表單post數據請求體

在express官方沒有內置獲取表單Post請求體的API,在此需要使用一個第三方包:body-parser

body-parser

安裝

npm install body-parser --save

配置

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// 配置 body-parser
// 只要加入這個配置,則在req請求對象上會多出來一個屬性:body
// 則可以直接通過req.body來獲取表單 POST請求的數據了
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())


使用

app.post('/post',function(req, res){
    var comment = req.body
    comment.dateTime = time.format(new Date(), 'YY-MM-DD')
    comments.push(comment)
    // 重定向
    res.redirect('/')
})

靜態服務

當我們直接訪問/public中的文件時候,是無法直接訪問的,則需要express.static來進行釋放文件,以來提供靜態資源服務

// 1. 通過public目下訪問,路徑前必須要求是 /public/xxx 之下的文件
app.use('/public/', express.static('./public/'))

// 2. 釋放public下的文件,訪問不加 public 直接 /xxx
app.use(express.static('./public/'))

// 3. 使用/pub/ 給/public/ 取別名,則需通過 /pub/xxx 訪問  public下的文件
app.use('/pub/',express.static('public'))
app.use('/pub/aa/',express.static('public'))	// 同樣可以這樣起別名

在Express中配置使用art-template模板引擎

安裝

npm install --save art-template
npm install --save express-art-template

配置

  • 配置使用 art-template 模板引擎
  • 第一個參數表示當以.art結尾的文件的時候,使用 art-template模板引擎
    • 需要渲染html文件時則可以將art修改爲html
// 雖然外面這裏不需要記載 art-template 但是也必須安裝
// 原因就在於 express-art-template 依賴了 art-template
	app.engine('art', require('express-art-template'));

使用

  • Express 爲 Response 相應對象提供了一個方法:render
  • render中第一個參數不能寫路徑,默認會去項目中的 views 目錄查找該模板文件,也就是說 Express 有一個約定:開發人員把所有的視圖文件都放到 views 目錄中
  • 如果想要修改默認的 views 目錄,則可以app.set('views', render函數的默認路徑)
app.get('/', function(req, res){
    // express 默認去views 目錄找index.html
   	res.render('index.html', {
        title: '這是一個標題'
    })
    // 	res.render('404.html')
	//  res.render('admin/404.html')	// 訪問 views 下的admin下的404.html
})

如果希望修改默認的views視圖渲染存儲目錄,可以:

// 修改views,修改render函數的默認路徑
// app.set('views', render函數的默認路徑)
	app.set('views', '/show')

重定向

redirect方法允許網址的重定向,跳轉到指定的url並且可以指定status,默認爲302方式。

格式:res.redirect([status], url);

// 跳轉到指定網址
res.redirect("https://mp.csdn.net/");
// 跳轉到首頁
res.redirect("/");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章