【问题标题】:What does express - app.get do?express - app.get 是做什么的?
【发布时间】:2017-03-08 09:27:26
【问题描述】:

我正在做一个 express 教程,我需要帮助理解这段代码:

在 routes/index 文件夹中是这段代码:

module.exports = (app) => {
  app.get('/api', (req, res) => res.status(200).send({
    message: 'Welcome to the Todos API!',
  }));

  app.post('/api/todos', todosController.create);
};

在使用它的应用程序文件中是这段代码,我不明白:

require('./server/routes')(app);

导出了一个函数,为什么这里用的是app作为参数?

【问题讨论】:

  • 这有帮助吗?

标签: express routes


【解决方案1】:

Express.js 支持以下与 HTTP 方法对应的路由方法:get、post、put、head、delete 等。因此,我们可以将 express 实例作为为我们处理路由的函数的参数传递。大多数教程中的 express 实例是这样创建的:

var express = require('express');
// And then we instantiate express
var app = express();

然后,我们可以通过将其作为参数提供给函数来访问单独文件中的 express 方法。

module.exports = (app) =>

在这里它可以被赋予任何名称,但称它为应用程序会让读者更清楚地了解一切。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    app 对象通常表示 Express 应用程序。 app.get(path, callback) 使用指定的回调函数将 HTTP GET 请求路由到指定的路径。

    如果它的 app.get('name') ,其中 'name' 是应用设置中的字符串之一,则返回名称应用设置的值。

    app.get() 有两个用例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2013-03-04
      相关资源
      最近更新 更多