将请求转发到备用请求处理程序,而不是重定向 [英] Forward request to alternate request handler instead of redirect

查看:82
本文介绍了将请求转发到备用请求处理程序,而不是重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Express的Node.js,并且已经知道response.redirect()的存在.

I'm using Node.js with express and already know the existence of response.redirect().

但是,我正在寻找更多类似于Java的forward()功能,该功能采用与重定向相同的参数,但是在内部转发请求,而不是让客户端执行重定向.

However, I'm looking for more of a forward() functionality similar to java that takes the same parameters as redirect, but internally forwards the request instead of having the client perform the redirect.

为澄清起见,我没有在其他服务器上进行代理.我想直接在同一应用实例中forward('/other/path')

To clarify, I am not doing a proxy to a different server. I'd like to forward('/other/path') directly within the same app instance

从快速文档看如何执行此操作显然并不明显.有帮助吗?

It wasn't apparently obvious how to do this from the express documentation. Any help?

推荐答案

您只需要调用相应的路由处理程序函数即可.

You just need to invoke the corresponding route handler function.

function getDogs(req, res, next) {
  //...
}}
app.get('/dogs', getDogs);
app.get('/canines', getDogs);

选项2:手动/有条件地调用单独的处理程序功能

app.get('/canines', function (req, res, next) {
   if (something) {
      //process one way
   } else {
      //do a manual "forward"
      getDogs(req, res, next);
   }
});

选项3:致电next('route')

如果您仔细订购路由器模式,则可以致电next('route'),这可能会实现您想要的.基本上,它表示要继续向下移动路由器模式列表",而不是调用next(),后者要表示向下移动中间件列表(通过路由器)".

Option 3: call next('route')

If you carefully order your router patterns, you can call next('route'), which may achieve what you want. It basically says to express 'keep moving on down the router pattern list', instead of a call to next(), which says to express 'move down the middleware list (past the router)`.

这篇关于将请求转发到备用请求处理程序,而不是重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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