express 基礎入門

express

官方文檔

1. 安裝

npm init  // 生成package.json文件
npm install express --save

2. 簡單使用

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

// GET
app.get("/test", function (req, res){
    res.send("Hello World, this is a test")
})

// POST
app.post('/', function (req, res) {
  res.send('Got a POST request')
})

// PUT
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

// DELETE
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})

// 允許所有的方法
app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

app.listen(port, ()=>{console.log('hello')})

3. 使用靜態文件

使用下面的代碼

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

那麼public下面的文件就可以訪問了

http://localhost:3000/css/style.css
http://localhost:3000/js/app.js


如果要使用多個靜態文件夾,多次調用即可

app.use(express.static('public'))
app.use(express.static('files'))
  • 將靜態文件放在一個特定的路徑下
// 統一放在/static路徑下
app.use('/static', express.static('public'))

// 當然最好使用
app.use('/static', express.static(path.join(__dirname, 'public')))

4. 路由

  • 簡單的方式
app.get('/about', function (req, res) {
  res.send('about')
})
  • 使用正則
// This route path will match acd and abcd.
app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

// This route path will match /abe and /abcde.
app.get('/ab(cd)?e', function (req, res) {
  res.send('ab(cd)?e')
})
  • 路由參數
// 使用 :param 進行標記
app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params) // 獲取所有的參數信息
})

// 也可以使用正則表達式進行約束
Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
  • 路由handler
//多個callback函數可以處理一個路由,但是要使用next跳轉到另一個回調函數中
app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})

5. res相關函數

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

6. app.route

使用app.route可以對一個路由同時進行多個方法的請求處理

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

7. express.Router

可以用來創建模塊化的路由處理

// birds.js
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router

// ----------------------------------------------- //

// another.js
var birds = require('./birds')

// ...

app.use('/birds', birds)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章