Start a web server with Node.JS and Express

I am a developer from Delhi, India
Search for a command to run...

I am a developer from Delhi, India
No comments yet. Be the first to comment.
DISCLAIMER: This might not be the most well-written article since I haven't written in a while and I just wanted to get back to writing with a short article about my experience of the day, so sorry about that I previously used this repository for my...

The release of NextJS 13 brought about a plethora of new and impressive features, with one standout being the updated data fetching and management process. The fetch API replaced the more complicated functions, including getServerSideProps, getStatic...

Looking for a safe and reliable way to authenticate users? Consider implementing magic links. They offer a secure alternative to traditional passwords and can help mitigate the risk of password leaks and forgotten passwords. Magic Link authentication...

Neovim is a powerful text editor that can be customized with plugins to enhance its functionality. In this article, we will explore the top 10 essential Neovim plugins. These plugins can help improve your Neovim experience by adding features such as ...

A type-safe and zero-runtime version of Tailwind CSS

Node.JS and Express are two of the most used technologies in the web development world right now. It powers some big sites like Paypal, Wall Street Journal, Shutterstock and a lot more.
Getting started with Node.JS and Express is very easy.
First, let's start off with creating a Node.JS project/directory. You can run the following two commands on the the terminal. Alternatively, you can create a folder from your file manager and open it in VS Code or any other code editor of your choice.
mkdir node-express-tutorial
cd node-express-tutorial
code . # for Visual Studio Code users

Run the following in the terminal.
npm init
You will be prompted with a few questions. You can press enter through most of them.
Alternatively, you can run
npm init -yif you want to skip through all the questions with the default value.

So, start with creating a file named index.js. You can name it anything, just make sure you end it with .js.
Conventionally, the file is named
index.js,server.jsorapp.js.
Like most NodeJS packages, you can install express using npm. Run:
npm install express

This will add express as a dependency in your package.json and also install it in your node_modules folder.

In your index.js file, write the following:
const express = require("express")
If you've used Node.JS before, this should look familiar. This line basically imports the express package. Now, to use express, you need to instantiate the imported function. So:
const express = require("express")
+ const app = express()
Now, you can use the app variable to start the server like so:
app.listen(3000, () => {
console.log(`๐ Server started on port 3000`)
}
You've basically already created a web server. You can run the app by running
node index.js

If you get something like in the above gif, you're good to go to the next step!
So now, we've started an express server but it doesn't know what it has to do when we're visiting the / route. Hence we get the error:

For this, add the following line of code before calling the app.listen function:
app.get('/', (req, res) => {
return res.send("Hello, World")
})
Let's go through this code:
app.get function. This takes in two parameters:/ route.request and response parameters which express provides us with. The res(response) gives us a send function with which we can send back a text response to the browser. Now, we need to restart the NodeJS server running. Go to the terminal where you had run node index.js and then hit Control-C. And then restart by typing node index.js again like so:

BONUS: Restarting the node server repeatedly becomes very annoying. To deal with this, there's a package called
nodemonwhich you can install and setup. For detailed instructions visit: https://livecode247.com/how-to-add-auto-reload-to-your-node-js-app
Now, refresh the page on the browser and you should see this:

For the final step, you can refactor the port number like this
+ const port = process.env.PORT || 3000;
- app.listen(3000, () => {
- console.log(`๐ Server started on port 3000`)
- }
+ app.listen(port, () => {
+ console.log(`๐ Server started on port ${port}`);
+ });
process.env.PORT returns the PORT environment variable which is set in many hosting providers so it is a good practice to use that instead of hardcoding a port. We're saying that if it doesn't exist, use port 3000.
Your final code in index.js should look like this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
return res.send("Hello, World");
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`๐ Server started on port ${port}`);
});
That's it for this tutorial! Now express has a lot more stuff to offer you. Just yesterday, MDN released it's new website and I found a very good in-depth tutorial on express. Do check it out here.