Express.js Hello World
The tradition of learning any new programming language or framework starts with a "Hello World" example. In Express.js, our Hello World will be a simple web server that responds with "Hello World" when you visit a URL.
Creating Your First Express App
Create a new file called
app.js (or index.js) in your project folder and add the following code:<!-- Import express -->const express = require('express');
<!-- Create an express application -->const app = express();
<!-- Define a route for the homepage -->app.get('/', (req, res) => { res.send('Hello World!');});
<!-- Start the server on port 3000 -->const PORT = 3000;app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`);});Understanding the Code
| Line | Explanation |
|---|---|
require('express') | Imports the Express module. |
express() | Creates an Express application instance. |
app.get() | Defines a route for GET requests to the specified path. |
res.send() | Sends the HTTP response. |
app.listen() | Starts the server and listens for connections on the specified port. |
Running Your Server
1. Save the file
2. In the terminal, run:
node app.js3. Open your browser and go to:
http://localhost:3000You should see "Hello World!" displayed in your browser!
Adding More Routes
Let's add a couple more routes to see how it works:
<!-- About page -->app.get('/about', (req, res) => { res.send('About Page');});
<!-- Contact page -->app.get('/contact', (req, res) => { res.send('Contact Page');});Two Minute Drill
- Create an Express app with `express()`.
- Define routes using `app.get()`, `app.post()`, etc.
- Start the server with `app.listen(port, callback)`.
- The callback function runs when the server starts successfully.
- Visit `http://localhost:3000` to see your app.
Need more clarification?
Drop us an email at career@quipoinfotech.com
