Express快速入門

王小奎發表於2020-11-03

安裝

$ npm init -y

安裝依賴包

$ npm install express --save

在專案中新建一個index.js檔案

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

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

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

執行index.js

node index.js

在網頁上訪問http://localhost:3001

基本路由

選路指的是確定應用程式如何響應客戶端請求到特定端點,即url和特定的http請求。

下面的示例說明如何定義簡單的路由。
用“你好”!在網頁上:

app.get('/', function (req, res) {
  res.send('你好!')
})

響應根路由上的post請求,訪問應用程式的主頁:

app.post('/', function (req, res) {
  res.send('我是post請求')
})

put請求的響應/user路線:

app.put('/user', function (req, res) {
  res.send('put請求')
})

對DELETE 請求作出響應。/user路線:

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