可以在收听时添加到Node.js Express的路由吗? [英] Okay to add a route to Node.js Express while listening?

查看:43
本文介绍了可以在收听时添加到Node.js Express的路由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,添加路线以表达的典型示例如下:

Obviously the typical example of adding routes to express follows something like the following:

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

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

app.listen(3000);

显然,在大多数情况下,你知道 get 路由在服务器开始侦听之前存在。但是如果你想在服务器监听时动态创建新路由怎么办?换句话说,我想做类似以下的事情:

Clearly, in most cases you know the get route exists before the server begins listening. But what if you want to dynamically create new routes once the server is listening? In other words, I want to do something like the following:

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

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

实际上,路线的回调显然是从一些远程源动态提取的。我已经测试了上面的代码,一切看起来都运行正常,但是,我希望得到确认,在我继续使用这种模式之前调用app.listen之后不会出现任何意外的副作用。

In practice the callback of the route would obviously be pulled dynamically from some remote source. I've tested the above code and everything appears to function properly, however, I was hoping to get confirmation that there wouldn't be any unintended side-effects of creating routes after app.listen is called before I move forward with this pattern.

注意:为了澄清,当我写主 server.js 将创建快速服务器的文件(因此在调用 listen 之前无法创建路由的原因)。在服务器启动/运行时,将从数据库中提取路由列表(及其各自的处理程序/回调函数)。

Note: To clarify, I don't know what the routes will be when I write the main server.js file that will be creating the express server (hence why I can't create the routes before listen is called). The list of routes (and their respective handlers/callback functions) will be pulled from a database while the server is starting up/running.

推荐答案

根据TJ (作者Express),可以在运行时添加路由。

According to TJ (author of Express), it’s okay to add routes at runtime.

主要问题是路由按照添加顺序进行评估,因此在运行时添加的路由将是优先级低于先前添加的路由。根据您的API设计,这可能或不重要。

The main gotcha is going to be that routes are evaluated in the order they were added, so routes added at runtime will have a lower precedence than routes added earlier. This may or may not matter, depending on your API design.

这篇关于可以在收听时添加到Node.js Express的路由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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