将请求转发给备用请求处理程序,而不是redirect

我用express来使用node.js,并且已经知道response.redirect()的存在。

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

为了澄清,我没有做一个不同的服务器的代理。 我想直接在同一个应用程序实例中转发('/ other / path')

如何从快速文档中做到这一点并不明显。 任何帮助?

你只需要调用相应的路由处理函数。

选项1:将多个path路由到相同的处理函数

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() ,它表示“向下移动中间件列表(通过路由器)”。

您可以通过更改请求url属性并调用next('route')来实现forward (aka rewrite )function。

请注意,执行forward的处理程序需要在您执行的其他路由之前进行configuration。

这是所有*.html文档转发到不带.html扩展名(后缀)的路由的例子。

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

next('route')作为最后的操作。 next('route')将控制权交给后续路线。

如上所述,您需要将forwards handlerconfiguration为第一个处理程序之一。

 app.get('*', forwards); // ... app.get('/someroute', handler); 

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

请注意,用于forwardsfunction的正则expression式被简化用于机制expression的目的。 如果你想使用查询string参数等,你需要扩展它(或者对req.path进行检查)。

我希望这会有所帮助。

 app.get('/menzi', function (req, res, next) { console.log('menzi2'); req.url = '/menzi/html/menzi.html'; // res.redirect('/menzi/html/menzi.html'); next(); }); 

这是我的代码:当用户input“/ menzi”时,服务器会给用户页面/menzi/html/menzi.html,但浏览器中的url不会改变;

如果下一个处理程序没有以正确的顺序添加,则使用next函数不起作用。 我使用路由器来注册处理程序和调用,而不是使用next

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

您可以使用run-middleware模块。 只需使用URL&method&data运行你想要的处理程序。

https://www.npmjs.com/package/run-middleware

例如:

 app.runMiddleware('/get-user/20',function(code,body,headers){ res.status(code).send(body) })