gpt4 book ai didi

node.js - express.js 中 app.use 和 app.get 的区别

转载 作者:IT老高 更新时间:2023-10-28 21:45:50 35 4
gpt4 key购买 nike

我对 express 和 node.js 有点陌生,我无法弄清楚 app.use 和 app.get 之间的区别。看来您可以同时使用它们来发送信息。例如:

app.use('/',function(req, res,next) {
res.send('Hello');
next();
});

好像和这个一样:

app.get('/', function (req,res) {
res.send('Hello');
});

最佳答案

app.use()用于绑定(bind) middleware到您的应用程序。 path 是“mount”或“prefix”路径,并限制中间件仅适用于请求 开始。它甚至可以用来嵌入另一个应用程序:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

通过将 / 指定为“mount”路径,app.use() 将响应任何以 开头的路径/,它们都是它们,并且与使用的 HTTP 动词无关:

  • GET/
  • PUT/foo
  • POST/foo/bar
  • 等等

app.get() ,另一方面,是 Express' application routing 的一部分。并且用于在使用 GET HTTP 动词请求时匹配和处理特定路由:

  • GET/

而且,您的 app.use() 示例的等效路由实际上是:

app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});

(更新:试图更好地展示差异。)

包括 app.get() 在内的路由方法是方便的方法,可帮助您更精确地调整对请求的响应。他们还增加了对 parameters 等功能的支持。和 next('route').

在每个 app.get() 中都是对 app.use() 的调用,因此您当然可以使用 app.use( ) 直接。但是,这样做通常需要(可能不必要地)重新实现不同数量的样板代码。

例子:

  • 对于简单的静态路由:

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

    对比

    app.use('/', function (req, res, next) {
    if (req.method !== 'GET' || req.url !== '/')
    return next();

    // ...
    });
  • 同一路由有多个处理程序:

    app.get('/', authorize('ADMIN'), function (req, res) {
    // ...
    });

    对比

    const authorizeAdmin = authorize('ADMIN');

    app.use('/', function (req, res, next) {
    if (req.method !== 'GET' || req.url !== '/')
    return next();

    authorizeAdmin(req, res, function (err) {
    if (err) return next(err);

    // ...
    });
    });
  • 带参数:

    app.get('/item/:id', function (req, res) {
    let id = req.params.id;
    // ...
    });

    对比

    const pathToRegExp = require('path-to-regexp');

    function prepareParams(matches, pathKeys, previousParams) {
    var params = previousParams || {};

    // TODO: support repeating keys...
    matches.slice(1).forEach(function (segment, index) {
    let { name } = pathKeys[index];
    params[name] = segment;
    });

    return params;
    }

    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);

    app.use('/', function (req, res, next) {
    if (req.method !== 'GET') return next();

    var urlMatch = itemIdPattern.exec(req.url);
    if (!urlMatch) return next();

    if (itemIdKeys && itemIdKeys.length)
    req.params = prepareParams(urlMatch, itemIdKeys, req.params);

    let id = req.params.id;
    // ...
    });

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

关于node.js - express.js 中 app.use 和 app.get 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15601703/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com