express 重定向
If you've created a site using Node.js, there's a great chance you've used the Express framework. Express has turned into a massive project and for good reason: it's loaded with useful functionality, an easy API, and massive community support. On of my recent projects was using Express and I loved it!
如果您使用Node.js创建了一个站点,那么您很有可能会使用Express框架。 Express已变成一个庞大的项目,这有充分的理由:它加载了有用的功能,简单的API和庞大的社区支持。 在我最近的项目中,有一个使用Express,我喜欢它!
One problem I recently needed to solve was creating a 301 redirect from an old staging domain to the new production domain. Here's how you can create that 301 redirect with Express:
我最近需要解决的一个问题是创建一个从旧暂存域到新生产域的301重定向。 使用Express创建301重定向的方法如下:
app.use(function forceLiveDomain(req, res, next) {
// Don't allow user to hit Heroku now that we have a domain
var host = req.get('Host');
if (host === 'serviceworker-cookbook.herokuapp.com') {
return res.redirect(301, 'https://serviceworke.rs/' + req.originalUrl);
}
return next();
});
Surprisingly the redirect code is the first argument to redirect
instead of the URL. It's important to call next()
at the end of the function or a non-match will make your app hang!
令人惊讶的是重定向代码是第一个参数redirect
,而不是URL。 在函数末尾调用next()
很重要,否则不匹配会使您的应用挂起!
express 重定向