基本路由

首先建立一個快速應用程式

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

然後你可以定義這樣的路線:

app.get('/someUri', function (req, res, next) {})

該結構適用於所有 HTTP 方法,並期望路徑作為第一個引數,並且該路徑的處理程式接收請求和響應物件。因此,對於基本的 HTTP 方法,這些是路由

// GET www.domain.com/myPath
app.get('/myPath', function (req, res, next) {})

// POST www.domain.com/myPath
app.post('/myPath', function (req, res, next) {})

// PUT www.domain.com/myPath
app.put('/myPath', function (req, res, next) {})

// DELETE www.domain.com/myPath
app.delete('/myPath', function (req, res, next) {})

你可以在此處檢視支援的動詞的完整列表。如果要為路由和所有 HTTP 方法定義相同的行為,可以使用:

app.all('/myPath', function (req, res, next) {}) 

要麼

app.use('/myPath', function (req, res, next) {})

要麼

app.use('*', function (req, res, next) {})

// * wildcard will route for all paths

你可以將路徑定義連結到單個路徑

app.route('/myPath')
  .get(function (req, res, next) {})
  .post(function (req, res, next) {})
  .put(function (req, res, next) {})

你還可以向任何 HTTP 方法新增函式。它們將在最終回撥之前執行,並將引數(req, res, next)作為引數。

// GET www.domain.com/myPath
app.get('/myPath', myFunction, function (req, res, next) {})

你的最終回撥可以儲存在外部檔案中,以避免在一個檔案中放入太多程式碼:

// other.js
exports.doSomething = function(req, res, next) {/* do some stuff */};

然後在包含你的路線的檔案中:

const other = require('./other.js');
app.get('/someUri', myFunction, other.doSomething);

這將使你的程式碼更清潔。