express.js 中 app.use 和 app.get 的区别 [英] Difference between app.use and app.get in express.js

查看:40
本文介绍了express.js 中 app.use 和 app.get 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm kind of new to express and node.js, and I can't figure out the difference between app.use and app.get. It seems like you can use both of them to send information. For example:

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

好像和这个一样:

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

推荐答案

app.use() 用于将 middleware 绑定到您的应用程序.pathmount"或前缀"路径,并将中间件限制为仅适用于开始.它甚至可以用来嵌入另一个应用程序:

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// 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 动词:

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

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

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

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET/

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

And, the equivalent routing for your example of app.use() would actually be:

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

<小时>

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

路由方法,包括 app.get(),是一种方便的方法,可帮助您更精确地将响应与请求对齐.他们还添加了对 parametersnext('路线').

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

在每个 app.get() 中是对 app.use() 的调用,因此您当然可以使用 app.use() 直接.但是,这样做通常需要(可能没有必要)重新实现各种样板代码.

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

示例:

  • 对于简单的静态路由:

  • For simple, static routes:

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

对比

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

  // ...
});

  • 同一路由有多个处理程序:

  • With multiple handlers for the same route:

    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);
    
        // ...
      });
    });
    

  • 带参数:

  • With parameters:

    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;
      // ...
    });
    

  • 注意:Express 对这些功能的实现包含在其RouterLayerRoute.

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

    这篇关于express.js 中 app.use 和 app.get 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆