Creating Your First Express Server
# CHAPTER 4
Creating Your First Express Server
1. Introduction
The foundation of any backend application is the server itself. It is the program that sits in memory, listening to a specific network port, waiting for incoming internet traffic. In this chapter, we will write the foundational code required to instantiate an Express application, define a basic route, and turn the server "on."2. Learning Objectives
By the end of this chapter, you will be able to:- Import and instantiate the Express module.
-
Understand the
appobject.
-
Define a basic
GETroute.
-
Use
app.listen()to start the server on a specific port.
3. Beginner-Friendly Explanation
Imagine opening a physical store.- 1. Importing Express: This is legally registering your business name.
-
2.
Instantiating
app: This is signing the lease for the building. You now have an empty store (const app = express();).
-
3.
Defining a Route: This is placing a cashier at the front desk and giving them a script: "When someone walks in and says 'Hello', you reply with 'Welcome'." (
app.get(...))
-
4.
Listening on a Port: This is unlocking the front doors and flipping the "Open" sign so customers can actually enter. (
app.listen(3000))
4. Step 1: The Code Skeleton
Ensure you have initialized your project and installed Express (npm install express), as covered in Chapter 2.
Create a file in your project root named index.js.
5. Step 2: Defining a Basic Route
Theapp object contains methods for HTTP verbs (get, post, put, delete). We will define a simple GET route for the homepage (/).
*Note: req represents the Request, and res represents the Response.*
6. Step 3: Starting the Server
Right now, the code exists, but it is not listening for traffic. We must use thelisten() method to bind the application to a port on our computer.
7. The Complete File
Here is your completeindex.js file:
8. Running the Server
Open your terminal, ensure you are in the project folder, and run:You will see Server is successfully running on http://localhost:3000 printed in the terminal.
Open your web browser (Google Chrome) and type http://localhost:3000 into the address bar. You will see your welcome message!
To stop the server, go to your terminal and press Ctrl + C.
9. Best Practices
-
Use Environment Variables for Ports: In professional applications, you should never hardcode
const PORT = 3000;. When you deploy to a cloud provider like Heroku or AWS, the cloud server assigns a random port dynamically. You should write:
const PORT = process.env.PORT || 3000;
*(This means: Use the cloud's port, but if it doesn't exist because we are on my local laptop, use 3000).*
10. Common Mistakes
-
The "Address Already in Use" Error: If you run
node index.jsand get anEADDRINUSE: address already in use :::3000error, it means you already have a Node server running in the background (or in another terminal window) that is occupying Port 3000. Stop the other server, or change this script's port to3001.
11. Exercises
-
1.
Trace the flow: You type
http://localhost:3000into Chrome and hit Enter. What exact code block inindex.jscatches this action, and how does it respond?
12. Coding Challenges
-
Challenge: Add a second route to your
index.jsfile. If the user visitshttp://localhost:3000/api/status, the server should useres.send()to reply with the text: "API is online and healthy". Run the server and test it in your browser.
13. MCQs with Answers
What is the purpose of the app.listen() method in Express?
When writing const PORT = process.env.PORT || 3000;, what does this code achieve?
14. Interview Questions
-
Q: Explain the role of the
reqandresobjects passed into an Express route callback function.
-
Q: Why do developers use
nodemoninstead of the standardnodecommand during development? What problem does it solve?
15. FAQs
Q: Can I useres.send() multiple times in one route?
A: No! You can only send *one* response per request. If you write res.send('A'); res.send('B');, Express will crash with a "Cannot set headers after they are sent to the client" error.
16. Summary
In Chapter 4, we brought our application to life. We imported the Express module, instantiated the coreapp object, and defined our very first HTTP GET route. By utilizing the app.listen() method, we bound our application to a network port, allowing it to successfully intercept web traffic from a browser and return a custom text response.
17. Next Chapter Recommendation
Our server is running, but it only knows one URL (/). Real applications have hundreds of URLs. Proceed to Chapter 5: Express Routing Basics.