我正在使用带有express的Node.js并且已经知道它的存在response.redirect().
但是,我正在寻找更多forward()类似于java 的功能,它采用与重定向相同的参数,但在内部转发请求而不是让客户端执行重定向.
为了澄清,我没有代理其他服务器.我想forward('/other/path')直接在同一个应用实例中
从快递文档中如何做到这一点并不明显.有帮助吗?
Pet*_*ons 22
您只需要调用相应的路由处理函数.
function getDogs(req, res, next) {
//...
}}
app.get('/dogs', getDogs);
app.get('/canines', getDogs);
Run Code Online (Sandbox Code Playgroud)
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)
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+
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)
| 归档时间: |
|
| 查看次数: |
34956 次 |
| 最近记录: |