搭建express服務器

express是一個基於Node.js的極簡的web應用程序開發框架。css

首先爲應用程序建立一個package.js文件html

npm init -y

在項目目錄添加index.js文件node

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

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

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

啓動web

node index.js

而後在瀏覽器中訪問http://localhost:3000/就能夠看到返回的'Hello wORLD!'文本了。express

路由指定了如何對對應的URI請求進行響應,例以下面的各類請求npm

app.get('/', function (req, res) {
  res.send('Hello World!')
})

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

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

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

靜態文件瀏覽器

爲了提供CSS文件、圖片、js文件之類的靜態資源,能夠使用express.static內置中間件函數。app

express.static(root, [options])

下面代碼對外開放了public目錄下的文件框架

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

而後就能夠直接訪問public目錄下面的文件了,Express 在靜態目錄查找文件,所以,存放靜態文件的目錄名不會出如今 URL 中。dom

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

能夠添加多個靜態資源目錄

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

能夠提供一個虛擬的訪問路徑,路勁真實並不存在,但訪問時須要加上。

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

訪問

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

也能夠提供一個絕對路徑

app.use('/static', express.static(path.join(__dirname, 'public')))

除了get、post等方法設置路由外,還能夠使用express.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')
  })

express.Router

使用express.Router()能夠建立一個模塊化的、可裝載的router處理函數。router能夠做爲middleware使用use加載,下面birds.js文件是一個Router模塊。

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

做爲中間件使用router模塊

var birds = require('./birds')

// ...

app.use('/birds', birds)

而後就能夠使用/birds and /birds/about訪問了

相關文章
相關標籤/搜索