node.js - 为什么链式 get()、post() 和 put() 方法不需要路径参数?

标签 node.js express routes

我正在通过各种教程学习 express,并且有一个本地运行的应用程序,但我想更好地理解代码的每个部分的作用。

我对此处 app.route() 部分中的示例有点困惑:

https://expressjs.com/en/guide/routing.html

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

我可以看到 app 等于 express(),这是记录在案的顶级函数 here .

我可以看到 .get()post()put() 方法链接到 route() 方法,记录在案 here .

我感到困惑的地方是,文档说明了 .get()post()put() 的参数方法采用这种格式:

app.get(path, callback [, callback ...])
app.post(path, callback [, callback ...])
app.put(path, callback [, callback ...])

为什么链式 .get()post()put() 方法不需要路径 参数,取而代之的是将单数函数作为参数,从 Request 返回值(又名 req)和 Response (又名 res)对象参数?

我显然遗漏了一些简单的东西,所以指向文档的指针可以帮助我更好地理解直接从 app 调用时这些方法之间的区别,例如 app.get(),以及来自 route(),例如 app.route('/book').get() 将不胜感激。

编辑: 基本上,我想知道是否有文档定义了 .get()post() 所需的参数格式put() 方法从调用 app.route("/book") 返回的路由对象调用时,因为它似乎不是什么已记录,即 path, callback [, callback ...]

最佳答案

app.route()

根据文档,app.route 方法:

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

这意味着,app.route() 只获取路径并返回route 对象。这将具有所有 http 动词方法来处理针对一条路径的中间件,getpostdeletepostput, patch

为什么?

简单地使用具有相同路径但不同 HTTP 请求的路由。喜欢:

app.route('/books')
  .get() // To get the list of objects
  .post() // To save a new book.

个别 HTTP 方法

另一方面,express 在 app 上提供了单独的方法来处理 HTTP 请求。像 app.get()app.post()app.delete()

As per docs for post route: HTTP POST requests to the specified path with the specified callback functions.

为什么?

对于多个 HTTP 请求没有一条路径的情况。比方说:

app.delete('/books/:bookId/comments/:commentId', function(){});

上述路由是一种单路由,仅用于删除某本书的特定评论。

我希望我能够消除差异。

Reference Link for the docs: https://expressjs.com/en/4x/api.html#router.route

编辑:

由于没有合适的文档可用,列出了路由对象提供的方法: 有关更多信息,请将 github 的链接添加到快速路由器。

https://github.com/expressjs/express/blob/master/lib/router/route.js

下面是 express 路由器的代码,它在所有方法上添加了处理程序。

methods.forEach(function(method){
  Route.prototype[method] = function(){
    var handles = flatten(slice.call(arguments));

    for (var i = 0; i < handles.length; i++) {
      var handle = handles[i];

      if (typeof handle !== 'function') {
        var type = toString.call(handle);
        var msg = 'Route.' + method + '() requires a callback function but got a ' + type
        throw new Error(msg);
      }

      debug('%s %o', method, this.path)

      var layer = Layer('/', {}, handle);
      layer.method = method;

      this.methods[method] = true;
      this.stack.push(layer);
    }

    return this;
  };
});

在顶部的这个文件中,它有:

var methods = require('methods');

methods: https://github.com/jshttp/methods

因此,链接方法所需的参数是unlimited functions作为请求handlers/middlewares

关于node.js - 为什么链式 get()、post() 和 put() 方法不需要路径参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247709/

相关文章:

javascript - 在 node.js mysql-node 查询中使用变量

node.js - 错误 TS1259 : Module '"./node_modules/@types/express/index "' can only be default-imported using the ' esModuleInterop' 标志

javascript - webpack-dev-middleware 不会将输出编译到文件夹中

express - 像 swagger/swashbuckle 但对于 node.js?

Symfony2/路由/使用参数作为 Controller 或操作名称

mysql - 连接 node.js 和 sphinx 的最佳方式

javascript - 带有回调的 Node.js setTimeout

javascript - 500 类型错误 : Not a string or buffer in express. js,node.js

javascript - 没有标签的 AngularJS 动态路由

Flutter:Autoroute:RouteGuard 在 AutoTabsScaffold 中不工作