Introduction
Hi all, today we'll be looking at a simple and beginner-friendly way to create your first RESTful route with Node and Express.
Overview
For those of you who aren't familiar with Node and Express. Node.js is simply an open source javascript web server environment that lets developers write command line tools and server-side scripts outside of a browser - (Learn more) couple that with Express.js Learn more, which is a backend web framework for Node that allows for setting up routes, middleware and dynamically render HTML pages.
In this tutorial we will be creating our first route using Node and Express to render a greeting, "Hello, World!" to a web page.
To Start
You should have some familiarity with a code editor or IDE (Integrated Development Environment) and have Node.js installed on your machine. I will be using VS Code for this demonstration. To find out how to install Node.js check out the docs here Installing node
Let's Begin
Open up VS Code or your favorite IDE and create a folder, name it whatever you'd like and we'll create a file named "index.js"
Installing Express
To use Express with Node we'll need to ensure we install Express, to do so, inside your root folder, open up your terminal - if you're on VSCode, simply guide your cursor to the top menu bar and click 'Terminal'
Inside of your terminal:
Run this command % npm i express
Now we need to define express at the top of our index.js by typing:
const express = require('express')
and we'll set app
const app = express()
Your file should look something like this:
This will facilitate our route and handle our simple get request. A GET request is an HTTP method.
Now copy and paste or type the following into index.js:
app.get('/', (req, res) => {
res.send('Hello, World!')
})
This code sets our "home" route, which in our case is just localhost:3000 and our express callback will take in two parameters (req, res)
which represents an HTTP request and response. We then send our message with res.send('Hello, World!')
Lastly, we will display a simple confirmation message to our console with the following code.
app.listen(3000, () => {
console.log("Listening on port 3000")
})
Your index.js file should look like this:
Finally, we can now run our node server by typing this command:
node index.js
You should see this in your terminal:
Now if we head over to localhost:3000 you should see
Awesome! Congratulations, you have successful built your first route with Node and Express. Woohoo! 🎉
Top comments (0)