Course Content
Backend Development with Node.js and Express.js
Backend Development with Node.js and Express.js
Setting up an Express App
Let's create our first backend app with Express.js. Are you ready to get started?
Installing Express.js
Create a new directory for the app, and open the folder in the code editor. We are ready to start. In the terminal, run this command:
It's like ordering Express.js from a virtual app store, and npm is our delivery service.
As a result, we get such file-folder structure of our app:
Basic project structure:
node_modules
- Contains installed packages;package.json
andpackage-lock.json
- List project dependencies and scripts;app.js
orindex.js
- Entry point for the Express application. We create it manually by ourselves.
🏗️ Build First Express App
Create a simple web server using Node.js and the Express.js framework. Follow the following steps:
Step 1: Import Express
As library we need firstly to import it to our file:
Step 2: Creating an Express Application Instance
We create an instance of the Express application. This app
variable will be used to configure and define the web server's behavior.
Step 3: Set the Port
We define the port number that our server will listen on. In this case, it's set to 3000, but we can choose any available port number.
Step 4: Defining a Route
We set up a route for handling HTTP GET requests to the root URL (/
). When a client (typically a web browser) accesses the server's root URL, it responds with Hello, World!
.
app.get('/')
- This defines a route for handling GET requests to the root path (/
). We can define routes for different HTTP methods (GET, POST, PUT, DELETE, etc.);(req, res) => { ... }
- This is a callback function that gets executed when a client makes a GET request to the specified route. It takes two arguments:req
(the request object) andres
(the response object). In this case, it simply sends theHello, World!
text as the response.
Step 5: Start the Server
Let's start the server and make it listen on the specified port (in our case, port 3000). When the server is successfully started, it logs a message to the console, indicating which port it is listening on.
app.listen(port, ...)
- This method starts the server and listens on the specified port. The second argument is a callback function that gets executed once the server is up and running.
Step 6: Run the App
We run the app in the terminal using node
command.
🌐 After running the script
Our server will be running, and we can access it by opening a web browser and navigating to http://localhost:3000
. You should see Hello, World!
displayed in your browser.
Thanks for your feedback!