简体   繁体   English

重定向express.js中的多个路由

[英]Redirecting multiple routes in express.js

I am working on an express app and am new to the framework. 我正在开发一个快速应用程序,并且是框架的新手。 I have a few routes I'd like to redirect to one without doing something like: 我有一些路线我想重定向到一个没有做类似的事情:

var router = require("express").Router();

router.all("/route", function(req, res){
    res.redirect("/repetitive");
});

router.all("/route2", function(req, res){
    res.redirect("/repetitive");
});

This is a contrived example, but I'm looking for a way to have many routes redirect to /repetitive without writing lots of router.all s , but I don't see a way in the docs. 这是一个人为的例子,但是我正在寻找一种方法让许多路由重定向到/repetitive而不需要写很多router.all s,但是我没有在文档中看到一种方法。 Is passing a regex to router.all an option and if so is that the best practice for express? 正在将一个正则表达式传递给router.all一个选项,如果是这样,那么表达的最佳做法是什么? Thanks! 谢谢!

What about the following? 以下怎么样?

var r = function(req, res) {
    res.redirect("/repetitive");
}

var routes = ["/route", "/route2"];
for (var i in routes)
    router.all(routes[i], r);

or if names follow a regular expression pattern: 或者如果名称遵循正则表达式模式:

router.all(/\/route\d*/, function(req, res) {
    res.redirect("/repetitive");
});

The above will match "/route" optionally followed by a number. 以上将匹配“/ route”,可选地后跟一个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM