转发请求到备用请求处理程序而不是重定向

use*_*174 36 node.js express

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

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

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

从快递文档中如何做到这一点并不明显.有帮助吗?

Pet*_*ons 22

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

选项1:将多个路径路由到同一个处理函数

function getDogs(req, res, next) {
  //...
}}
app.get('/dogs', getDogs);
app.get('/canines', getDogs);
Run Code Online (Sandbox Code Playgroud)

选项2:手动/有条件地调用单独的处理函数

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

选项3:通话 next('route')

如果你仔细订购你的路由器模式,你可以打电话next('route'),这可能达到你想要的.它基本上表示要"继续沿路由器模式列表继续前进",而不是呼叫next(),表示"向下移动中间件列表(通过路由器)".


Tom*_*Tom 18

您可以通过更改请求属性和调用来实现前向(也称为重写)功能.urlnext('route')

请注意,执行转发的处理程序需要在您执行的其他路由之前配置.

这是所有*.html文档转发到没有.html扩展名的路由(后缀)的示例.

function forwards(req, res, next) {
    if (/(?:.+?)\.html$/.test(req.url)) {
        req.url = req.url.replace(/\.html$/, '');
    }
    next('route');
}
Run Code Online (Sandbox Code Playgroud)

你打电话next('route')为最后一次操作.将next('route')控制传递到随后的路由.

如上所述,您需要将转发处理程序配置为第一个处理程序之一.

app.get('*', forwards);
// ...
app.get('/someroute', handler);
Run Code Online (Sandbox Code Playgroud)

上面的示例将返回相同的内容/someroute以及/someroute.html.您还可以为对象提供一组前向规则({ '/path1': '/newpath1', '/path2': '/newpath2' })并在前向机制中使用它们.

请注意,forwards函数中使用的正则表达式是为了机制表示而简化的.req.path如果您想使用查询字符串参数等,则需要对其进行扩展(或执行检查).

我希望这会有所帮助.


小智 9

next如果未按正确的顺序添加下一个处理程序,则使用该函数不起作用.而不是使用next,我使用路由器注册处理程序和调用

router.get("/a/path", function(req, res){
    req.url = "/another/path";
    router.handle(req, res);
}
Run Code Online (Sandbox Code Playgroud)

  • 在Express 4+上不推荐使用路由器 (3认同)
  • 而不是router.get和router.handle,我在Express 4+中使用app.get和app.handle,它就像一个魅力!救了我!这应该被标记为正确的答案,因为这是唯一正确的答案. (3认同)
  • **对于 Express 4+** 使用 `req.app.handle` 而不是使用 `router.handle` (2认同)

Lor*_*ren 8

对于Express 4+

next如果未按正确的顺序添加下一个处理程序,则无法使用该功能。next我不使用而是使用路由器注册处理程序并调用

app.get("/a/path", function(req, res){
    req.url = "/another/path";
    app.handle(req, res);
}
Run Code Online (Sandbox Code Playgroud)

或用于React / Angular的HTML5模式

const dir = process.env.DIR || './build';

// Configure http server
let app = express();
app.use('/', express.static(dir));

// This route sends a 404 when looking for a missing file (ie a URL with a dot in it)
app.all('/*\.*', function (req, res) {
    res.status(404).send('404 Not found');
});

// This route deals enables HTML5Mode by forwarding "missing" links to the index.html
app.all('/**', function (req, res) {
    req.url = 'index.html';
    app.handle(req, res);
});
Run Code Online (Sandbox Code Playgroud)