Node.js 基本路由

示例

首先创建一个快递应用程序:

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

然后,您可以定义如下路线:

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

该结构适用于所有HTTP方法,并且期望将路径作为第一个参数,并将该路径的处理程序用作接收请求和响应对象的处理程序。因此,对于基本的HTTP方法,这些是路由

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

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

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

// 删除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) {})

// *通配符将路由所有路径

您可以将路径定义链接为一条路径

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

您还可以将函数添加到任何HTTP方法。它们将在最终回调之前运行,并以参数(req,res,next)作为参数。

// 获取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);

这将使您的代码更整洁。