express(Node.js)

原生的http在某些方面表現不足以應對咱們的開發需求,使用框架能夠加快咱們的開發效率html

1. 安裝

mkdir express
     cd express
     npm init -y
     npm install express --save
複製代碼

2. hello word

var express = require('express')
    var app = express()
    app.get('/', function (req, res) {
      res.send('hello world')
    })
    app.listen(3000, function () {
      console.log('express app is running ...')
    })
複製代碼

3. 基本路由(請求方法+請求路徑+請求處理函數)

app.get('/', function (req, res) {
  res.send('hello world')
})
app.post('/',function (req, res){
 res.send('hello world')
}
複製代碼

4. 靜態服務(統一處理靜態資源)

輸入url地址:/public/xxx
app.use('/public/', express.static('./public/'))
輸入url地址:/a/xxx
app.use('/a/', express.static('./public/'))
輸入url地址:xxx
app.use(express.static('./public/'))
複製代碼

5. 在express配置中使用模板art-template

  • 安裝
npm install --save art-template
    npm install --save express-art-template
    //express-art-template依賴了art-template,因此要一塊兒下載
複製代碼
  • 配置
app.engine('html', require('express-art-template')
複製代碼
  • 使用
app.get('/', function (req, res) {
    //express 默認去項目的viwe目錄下找index.html
      req.render('index.html', { 
        title:'hello word' 
      })
    }
複製代碼

6. 在express中獲取表單Get請求參數

  • express內置了一個api,能夠經過req.query獲取

7. 在express中獲取表單post請求體數據

  • 安裝express

    npm install body-parser --savenpm

  • 配置json

var express = require('express')
    var bodyParser = require('body-parser')
    var app = express()
    
    //配置 body-parser 中間件(插件,專門用來解析表單 POST 請求體)
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    
    app.use(function (req, res) {
      res.setHeader('Content-Type', 'text/plain')
      res.write('you posted:\n')
     //req請求對象中就會多一個body屬性,也就是經過req.body表單post請求體數據
      res.end(JSON.stringify(req.body, null, 2))
    })
複製代碼
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息