快速.js路由器中的自定义处理程序

Custom handler in express.js router

本文关键字:自定义 处理 程序 js 路由器 快速      更新时间:2023-09-26

>我正在为简单的膳食信息页面工作,我需要在一个进程中运行静态和动态 (json) 服务器,如下所示:

*- root
  +- index.html
  +- res
  | +- main.js
  | +- index.css
  | `- (and more)
  +- meal
  | `- custom handler here (json reqestes)
  `- share
    `- (static files, more)

静态文件会用express.static处理,我可以用快递路由吗?

所有不以/meal/开头的请求都应作为静态请求,如/res 或 (root)/anyfolder/anyfile

app.use('/share', express.static('share'));使静态处理程序看起来share/,而不是项目根目录。共享整个根是不寻常的,因为人们可以阅读您的源代码。你真的需要服务整个文件夹吗?例如,你能不能把res/放在share/里面,然后做一个指向res -> share/res/的符号链接,然后当客户端发出请求时res/main.js表达知道在share/res/main.js中查找。

无论如何,@hexacyanide的代码应该处理您的情况,只需确保对中间件函数进行排序,以便 Express 在静态文件之前处理路由函数:

app.use(app.router)
app.use('/share', express.static('share'));
app.get('/meal/:param', function(req, res) {
  // use req.params for parameters
  res.json(/* JSON object here */);
});
// if you want to prevent anything else starting with /meal from going to
// static just send a response: 
//app.get('/meal*', function(req, res){res.send(404)} ); 
app.get('/', function(req, res) {
  res.sendfile('index.html');
});

是的,这可以通过 Express 完成。您的设置可能如下所示:

app.use('/share', express.static('share'));
app.get('/', function(req, res) {
  res.sendfile('index.html');
});
app.get('/meal/:param', function(req, res) {
  // use req.params for parameters
  res.json(/* JSON object here */);
});

其中,您有一个静态文件服务器挂载到 /share 并路由到名为 /share 的目录,/ 处发送名为 index.html 的文件的路由,以及接受参数的路由,该参数使用 JSON 响应。

路由未捕获的任何内容都将尝试由静态文件服务器处理。如果文件服务器找不到文件,则它将以 404 响应。