roxxhub

How to create a web app using Express ?

What is express ?

Express, also sometimes referred as express.js is a Node.js framework used to create backends of websites.

In this tutorial, we’ll be seeing how express can be used to do so. We’ll be also pointing out key things one should always keep in mind while using express.

To do so we’ll be needing a code editor, vscode most preferably. And of course you should also be having Node.js installed in your computer

Creating the project folder

First we’ll simply create our project folder, inside where we’ll be doing everything. You can do that by typing

mkdir my-site
cd my-site

in your terminal.

We have named our project ‘my-site’.

Creating package.json

npm init

Installing express and other important modules

npm i express
npm i nodemon --dev

Although you can be using many helpful modules in your express app, we’ll be just using one additional module in ours, that is nodemon.

nodemon simply restarts our web server whenever we save some changes in our code. So now we won’t have to start our server manually every time we make some changes We’ll be using it as a devDependency.

Starting our server

To start our server, you need a create a file (lets say server.js) and copy the following code there

const express = require('express')

const app = express()
const port = 5000

app.get('/', (req, res) => 
             res.send('Hello World!'));


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Then type this in the terminal

nodemon server.js
express

If you get this output, this means our server has stared successfully and can now be accessed by localhost:5000.

express minimal app

Congratulations ! You have created the most basic (ugly) website using express !

Alright lets see things more closely now.

First we imported our express module. Then we created an object app, which can use every express method. Also remember to call the function when creating the app objects.

Then we called the ‘get’ method which is one of the many http methods that are available in express too. It basically takes two arguments, first an endpoint, or simply a webpage that might exist in your site. “/” refers to the main page itself. It also takes a function.

This function too gets two arguments req( user’s request) and res(response). To send data to the user, we use res.send function. Ideally, you would want to replace ‘hello world’, with some html.

You can create more routes like these

app.get('/', (req, res) =>
    res.send('this is homepage'));

app.get('/about-us', (req, res) =>
    res.send('this is about us'));

app.get('/dashboard', (req, res) => 
    res.send('this is your dashboad'));

Routers

Creating every endpoint or route of your website on a single file might be tedious, and to make this simpler, we’ll be using something called an express router.

The sitemap of your site might look like this

express app routes

Routers would help us to break the process of making each and every endpoint on a single file.

To do so first, you might wanna create a new folder and name it something like ‘routes’. Inside this you will have all your routes. make a .js file for both /about and /dashboard endpoints.

For dashboard.js file you might need to do the following stuff. (Routers give you every function/method, general express object gives)

const express = require('express')
const router = express.Router();


router.get("/", (req, res) =>{
    res.send("you are in your dashboard")
});

router.get("/friends", (req, res) =>{
    res.send("these are your freinds")
});

router.get("/posts", (req, res) =>{
    res.send("these are your posts")
});

router.get("/channels", (req, res) =>{
    res.send("these are your subbed cannels")
});

router.get("/posts/latest", (req, res) =>{
    res.send("these are your subbed cannels")
});

router.get("/posts/oldest", (req, res) =>{
    res.send("these are your subbed cannels")
});

module.exports = router

Then in the server.js file, you need to import this router like this.

const express = require('express')

const dash_router = require("./routes/dashboard")


const app = express()
const port = 5000

app.use("/dashboard", dash_router)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Like wise you need to do that for /about or any other endpoint you want. You get the idea.

Templating

Just like routers you may even want your html files / templates in a separate folder too. (We were just returning plain text as a response to the user till now, but you will put some html inside it instead).

Luckily its easy to do that too.

Simply create a template folder. Inside this maybe you wanna create the html template for the main ‘dashboard’ page.

Like this one from I found in w3schools. Then instead of send method, we will use the sendFile method. (notice we also use a module called path too)

You might wanna update your dashboard.js like this

const express = require('express')
const path = require("path")

const router = express.Router();

router.get("/", (req, res) =>{
    res.sendFile(path.join(__dirname, "../templates/homepage.html"))
});

router.get("/friends", (req, res) =>{
    res.send("these are your friends")
});

This way you get this when you go to /dashboard.

express templates

Conclusion

Express is one of the most trending, powerful and easy to use backend frameworks. Although we just touched the basics, there is still a lot left. In fact, almost every time there are many other modules and tools used simultaneously with express to create backends.

But I hope this gives its basic introduction to you.

1 thought on “How to create a web app using Express ?”

Comments are closed.