301 Redirect with 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!
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:
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!
Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...
While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready? Promises are becoming a big part of the JavaScript world...
Providing users as many preferences as possible always puts a smile on the user's face. One of those important preferences is font size. I can see fine but the next guy may have difficulty with the font size I choose. That's why...
Chris Coyier authored a post titled Better Pull Quotes: Don't Repeat Markup a while back. In his post he created great-looking pull quotes without repeating any content -- instead he uses jQuery to dynamically create the pull quotes. The following is the...
Great code snippet and saved me a ton of time. Thanks!
You shouldn’t have the trailing slash after serviceworke.rs. I.e. instead of this:
It should be this:
Otherwise it redirects to: