Basic Redirect with ExpressJS

Benjamin Cunningham
letsboot
Published in
2 min readFeb 2, 2018
VS Code

I am about to start working at a start-up located in Basel, Switzerland as an trainer’s assistant & web developer at letsboot.com. We teach various technologies like React(JS), Angular, NodeJS, Ionic, Docker and even Ethereum Solidity Smart Contract development.

Check out our Angular in-house trainings or a public Angular courses.
Try out fossilo.com, our angular project to archive complete websites.

Here is a basic tutorial of how to do a basic redirect using NodeJS and ExpressJS.

Simple redirects with ExpressJS and NodeJS.

To simplify matters, I’ll create a git repository and give a few tricks when working on the same project with different operating systems.

First start by creating or cloning a git repository:

// Create a new git repository and add the following commands in 
// your terminal:
echo "# test" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin git@github.com:UserName/test.git
git push -u origin master
// This is the repository of this tutorial for reference:
git clone git@github.com:Ul1ra/basicRedirect.git

Then open the chosen directory using your favourite code editor (for me it’s Visual Studio Code):

$ cd basicRedirect/
$ code .

To simplify working with different operating systems like OS X, create a .gitignore file and copy paste the following file from: https://gist.github.com/euoia/aa6d3a58476c98f047bb.

In the terminal add the following commands:

npm init
/* Gives you the ability to add or change different. Don't forget to add a description, some keywords, and a license like MIT. */
npm install --save express
/* Installs express. --save adds the dependencies to the project so any computer can run it without installing anything themselves. */
npm install --save nodemon
/* Restarts the NodeJS application whenever a change is made for faster testing. */

Finally create an index.js file to the repo and add the following information in:

const express = require('express');
const app = express();
const targetBaseUrl = 'http://www.letsboot.com/';
function handleRedirect(req, res) {
const targetUrl = targetBaseUrl + req.originalUrl;
res.redirect(targetUrl);
}
app.get('*', handleRedirect);const port = process.env.port || 3000;
app.listen(port);

Now once ‘npm start’ is running in the terminal, enter ‘localhost:3000' into your browser and you will automatically redirected to http://letsboot.com. To understand the code in depth, check this video out:

--

--

Benjamin Cunningham
letsboot

I live in Basel, CH and I aim to become a front end web developer. I have started working as a Co-Trainer and a Software Engineer at Letsboot.