A Beginner's Guide to Express.js & Node.js
learn to create servers using express.js
What exactly is Node.js?
Till now, you've been executing your JavaScript inside the browser. Here's where Node comes in. According to nodejs.org, "Node.js® is an open-source, cross-platform JavaScript runtime environment". What this means is that Node doesn't depend on the browser to run JavaScript. A JavaScript engine is something that runs JavaScript code. All browsers have their versions of JavaScript engines. Node has one as well. Node lets you write server-side scripts. What this means is that your server produces responses dynamically based on the client's request.
One reason to use Node is that it allows you to deal with databases. You can store stuff in a database and use it however you like. Node allows you to render web pages dynamically as well.
How do I start?
First, install the latest LTS version of Node from https://nodejs.dev/en/download/.
Create a JavaScript file, say 'app.js'. Type in console.log("Hello world!")
. Run your file in the terminal by saying node app.js
. Make sure you do this while in the same directory as your file. There, you've run your first Node app. You should see the message being logged in the terminal.
Enter npm
You’re not learning Node to print out hello world. Let's try creating a server. NPM is the standard package manager that comes with Node. Packages contain files for the modules that you'll be using often. One such package is Express.js. To install Express, just pop into the terminal and enter
npm i express
Servers in Express
A web server is software that accepts HTTP requests, usually sent by a browser, and sends a response (usually a webpage). Express is a framework that allows you to build web servers, frameworks, and REST APIs effectively. Let's take a look at a very simple server built using Express.
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("hello there");
});
app.listen(3000);
To use Express, or any other module for that matter, we need to require it in our project. Next, we create an express app using express(). An express app has methods to deal with HTTP requests, render views, and many other things.
app.listen(3000)
simply tells the app to listen for requests at port 3000. A port number (3000 here) is a way to identify a connection endpoint.
app.get("/", (req, res) => { res.send("hello there"); });
GET is an HTTP request method. It suggests that the client is trying to request data from the server. Here, the callback function is invoked whenever the browser sends a GET request to the "/" path. The path is relative to the root.
The callback function takes in two parameters, the request and the response. The request contains information like the method, the URL, and other data the client wishes to send. The response is sent back by the server. res.send() automatically sets the headers based on the type of response sent.
Sending a GET Request
Start the server using Node. In the browser, go to localhost:3000. You'll see the text hello world. This is the response sent by the Express server.
HTTP Status Codes
Restart the browser. Head over to the network tab in the developer tools and go to localhost:3000. You'll probably see a status code 200 for the request sent. Status codes are sent by the server for all client requests. These indicate if an HTTP request has been completed.
The popular status code 404 indicates that the server cannot find the resource that the browser is trying to access. You can find the list of all the status codes out there on the MDN Docs.
View Engines
View engines or template engines allow you to use templates to render your pages. These prevent cluttering and replace variables at runtime. Some common view engines are Pug, EJS, and Mustache. Jade is the view engine present as default in Express.
EJS
Install ejs by running npm i ejs in the terminal. Create a folder called views in your project folder. Inside 'views', create a file called index.ejs. Inside index.ejs, write some simple HTML.
Inside your app.js, require()
the ejs module the same way you did with Express. Put in the following code after creating your Express app: app.set("view engine", "ejs");
This sets the value of "view engine" to "ejs". Express worries about loading the module, so you don't need to. Inside your app.get() callback, replace the res.send()
with res.render("index");
Your code should look something like this:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
// res.send("hello there!"); //you need to remove this
})
app.listen(3000);
Run the app using Node and go to localhost:3000 in your browser. You should see that the web page is rendered.
Conclusion
Congratulations! You’ve learned the basics of how to use Node, how to create an express server, and how to use a view engine.
Before You Leave
Say hi:
This is my first post on here. Feel free to leave helpful suggestions below. If you spot any mistakes, please inform me. Hope you enjoyed the article. Thanks for reading.
Attributions
Illustrations:
https://storyset.com/illustration/playful-cat/bro, https://storyset.com/web, https://storyset.com/animal