Nodejs中express的app.get() 怎样理解?

Nodejs中express的app.get() 怎样理解?

表示对所谓 Web 框架只停留在写一下 app.get() 那种水平… 帖子写一半想起去看源码… 怎么偏偏找不到 app.get = 的具体代码 https://github.com/visionmedia/express/blob/master/lib/application.js

首先在前边看到获取变量的解释:

Get setting name value

app.get('title');

而后面又是我更熟悉的处理 GET 请求的用法…

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

这是为什么?

还有 app.params() app.use() app.engine() 我还好理解, 可前边的 app.set() 设置那么多变量那是做什么用的?

6 回复

Node.js 中 Express 的 app.get() 如何理解?

1. 理解 app.get()

在 Express 中,app.get() 主要用于定义处理 HTTP GET 请求的路由。它允许你将特定路径(如 /)与一个回调函数关联起来,该函数会在匹配到该路径时被调用。

2. 示例代码

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

// 定义一个处理 GET 请求的路由
app.get('/', function(req, res) {
    res.send('Hello World!');
});

// 启动服务器
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

在这个例子中,当用户访问 http://localhost:3000/ 时,服务器会返回 “Hello World!”。

3. app.get() 的内部实现

虽然你可以在 Express 的源码中找到 app.get 方法的定义,但更常见的是通过阅读文档来了解它的用法。app.get 是基于 app.METHOD() 方法实现的,其中 METHOD 可以是 get, post, put, delete 等 HTTP 方法。

Express 的核心逻辑是在 lib/router/index.js 文件中实现的,你可以在这里找到 router.METHOD() 的具体实现。例如:

/**
 * Define a `METHOD` routing path.
 *
 * Method overloading is supported, when multiple paths are given the
 * middleware will unroll to multiple route objects, where each one
 * contains an isolated copy of the middleware.
 *
 * @param {String|Array} path
 * @param {Function|Function[]} callbacks...
 * @return {Layer}
 * @api public
 */

prototype.METHOD = function(path, ...callbacks) {
    assertPath(path);
    if (typeof callbacks[callbacks.length - 1] === 'function' && !this.handle_options) {
        this.handle_options = callbacks[callbacks.length - 1];
    }
    const route = this.route(path);

    for (let i = 0; i < callbacks.length; i++) {
        route[method](callbacks[i]);
    }

    return route;
};

4. app.set() 和其他方法

app.set() 用于设置应用级别的配置选项,比如模板引擎、视图文件夹路径等。这些设置可以被路由和其他中间件使用。

例如:

app.set('view engine', 'ejs'); // 设置默认的视图引擎为 EJS
app.set('views', './views');   // 设置视图文件夹的路径

5. 总结

  • app.get() 用于定义处理 GET 请求的路由。
  • app.set() 用于设置应用级别的配置选项。
  • 其他类似的方法(如 app.use(), app.engine())用于不同的用途,帮助构建和管理 Express 应用。

希望这能帮助你更好地理解 app.get() 在 Express 中的作用!


/**
 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.
 */

methods.forEach(function(method){
  app[method] = function(path){
    if ('get' == method && 1 == arguments.length) return this.set(path); 
    var args = [method].concat([].slice.call(arguments));
    if (!this._usedRouter) this.use(this.router);
    return this._router.route.apply(this._router, args);
  }
});

若调用app.get()时只有一个参数,则认为是取设置值,否则认为是注册路由

终于有点懂了, 所有被 app.use() 接收的 handle 会被放到一个 stack 里边 app.get() 执行的时候会把一条路由规则添加到 stack 里… 然后顺序检索 statck 直到结束, 那么执行这段代码给出 404 https://github.com/senchalabs/connect/blob/master/lib/proto.js#L122

    // all done
    if (!layer || res.headerSent) {
      // delegate to parent
      if (out) return out(err);
  // unhandled error
  if (err) {
    // default to 500
    if (res.statusCode &lt; 400) res.statusCode = 500;
    debug('default %s', res.statusCode);

    // respect err.status
    if (err.status) res.statusCode = err.status;

    // production gets a basic error message
    var msg = 'production' == env
      ? http.STATUS_CODES[res.statusCode]
      : err.stack || err.toString();

    // log to stderr in a non-test env
    if ('test' != env) console.error(err.stack || err.toString());
    if (res.headerSent) return req.socket.destroy();
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', Buffer.byteLength(msg));
    if ('HEAD' == req.method) return res.end();
    res.end(msg);
  } else {
    debug('default 404');
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    if ('HEAD' == req.method) return res.end();
    res.end('Cannot ' + req.method + ' ' + utils.escape(req.originalUrl));
  }
  return;
}

不过这样的话, 自己定义 404 页面是怎样做到的 https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js#L45

真的理解错了… 谢谢指导, 现在明白过来了 原来 app.router 是单独的一个和 middleware 平级的对象 http://nodejs.iteye.com/blog/1594920

app.use(express.logger(...));
app.use(express.bodyParser(...));
app.use(express.cookieParser(...));
app.use(express.session(...));
app.use(app.router);
app.use(express.static(...));
app.use(express.errorHandler(...));

app.get() 是 Express 框架中用于定义处理 HTTP GET 请求的路由的方法。它允许你根据 URL 路径来匹配请求,并执行相应的回调函数来响应客户端的请求。

示例代码

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

// 定义一个处理根路径('/')的 GET 请求的路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 启动服务器监听端口
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

在这个例子中,当客户端向服务器发送一个 GET 请求到 http://localhost:3000/ 时,Express 将会调用定义的回调函数,并返回 “Hello World!” 字符串。

app.get() 的工作原理

app.get() 方法实际上是在内部使用 app.METHOD() 实现的,其中 METHOD 是 HTTP 方法(如 GET、POST 等)。当你调用 app.get() 时,Express 会在内存中存储一个路由记录,这个记录包含路径模式(如 '/')和对应的处理函数。

app.set()app.get()

app.set()app.get() 主要用于设置和获取应用级别的配置选项或变量。例如:

app.set('title', 'My App');

console.log(app.get('title')); // 输出: My App

这些配置可以用来管理应用程序的行为,比如设置模板引擎的默认选项、视图目录等。你可以将这些配置视为应用程序的全局设置。

希望这能帮助你更好地理解 app.get() 在 Express 中的作用及用途。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!