基本路由

首先创建一个快速应用程序

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);

这将使你的代码更清洁。