You’ll learn to build a simple server with Express in this lesson.
We use Express here because:
- It’s easier to use Express compared to building a server from scratch with Node internal functions.
- Express is the most popular server framework for Node JS. (Other popular options include Fastify and Koa).
Let’s begin.
Installing Express
We can install Express with npm.
npm install express -SStarting the server
Our server needs to listen for connections before it can do anything with those connections.
To listen to a connection, we can use Express’s listen method.
This listen method needs a port, which is a number value you use in the origin. We’ll use the port 3000 for this project.
import express from 'express'const app = express()const port = 3000
app.listen(port, () => { console.log(`Listening at http://localhost:${port}`)})People normally use either 3000 or 8080 for web development, but there are
no hard and fast rules here. You can pick any port number you like as long as
it lies between 1024 and 49151.
If you run the server now you should see a message like this:
Listening to the index page
We can listen to the index page with the following code:
app.get('/', (req, res) => { res.send('Hello World!')})If you run the server and visit the index page at http://localhost:3000, you should get a Hello World message.
Stopping the server
You can stop the server by pressing Control + C on your keyboard.
Remember this keyboard shortcut as you’ll use it often in your programming career.
Wrapping Up
You learned three things in this lesson:
- How to create a simple server with Express
- How to listen to the
indexpage - How to stop the server
Let’s proceed to the next lesson where you’ll learn about the two kinds of servers you can create.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson