搭建express服務器


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

首先為應用程序創建一個package.js文件

npm init -y

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

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!'))

啟動

node index.js

然后在瀏覽器中訪問http://localhost:3000/就可以看到返回的'Hello wORLD!'文本了。

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

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內置中間件函數。

express.static(root, [options])

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

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

然后就可以直接訪問public目錄下面的文件了,Express 在靜態目錄查找文件,因此,存放靜態文件的目錄名不會出現在 URL 中。

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訪問了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM