ExpressJS Hello World and Your First Server
Now that Express is installed let's create the simplest possible web server – the "Hello World" of Express. This example will show you how to create a server that responds with a friendly message when you visit it in your browser.
Create the Main File
In your project folder create a file called
app.js (or index.js – the name doesn't matter but we'll use app.js). Open it in your code editor.Write the Code
// 1. Import Express
const express = require('express');
// 2. Create an Express application
const app = express();
// 3. Define a route for the home page
app.get('/', (req, res) => {
res.send('Hello World! Welcome to my first Express server!');
});
// 4. Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});Step-by-Step Explanation
- Import Express: We use
require('express')to load the Express module. This returns a function. - Create an app: We call that function (
express()) to create our Express application. Thisappobject has methods for routing middleware and more. - Define a route:
app.get()tells Express to respond to HTTP GET requests at the specified path (here the root '/'). The callback function receives the request (req) and response (res) objects. We useres.send()to send the string back to the client. - Start the server:
app.listen(3000 callback)starts a server on port 3000. The callback runs once the server is ready and we log a message so we know where to go.
Run the Server
Go back to your terminal and run:
node app.jsYou should see:
Server is running on http://localhost:3000. Now open your browser and visit http://localhost:3000. You'll see your welcome message displayed!Understanding app.listen() in Detail
The
app.listen() method binds the server to a specific port and host (by default localhost). The callback function runs once the server is successfully started. This is useful for logging or performing any startup tasks.You can also store the server instance returned by
app.listen() to close it later if needed (for example in testing).const server = app.listen(3000, () => {
console.log('Server is running...');
});
// Later to close the server
server.close();Port Number Configuration
Ports are like doors into your computer. Different applications use different ports. For web servers common ports are 3000 5000 or 8080. In production you might use port 80 (HTTP) or 443 (HTTPS). It's a good practice to make the port configurable via environment variables:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});Basic Folder Structure for Your Express Project
As your app grows you'll want to organize your code. Here's a simple but effective folder structure for a small Express project:
my-express-app/
├── node_modules/
├── public/ # Static files (CSS images client-side JS)
├── routes/ # Route handlers
│ └── index.js
├── views/ # Template files (if using a view engine)
├── app.js # Main application file
├── package.json
└── .gitignoreWhat Goes Where?
- public: For static assets like stylesheets images and frontend JavaScript files. Express can serve them automatically using
express.static(). - routes: Separate files for different groups of routes (e.g. user routes product routes). This keeps
app.jsclean. - views: If you're using a template engine (like EJS or Pug) store your templates here.
- app.js: The entry point where you configure middleware mount routes and start the server.
Example: Organizing Routes
In
routes/index.js:const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Home Page');
});
router.get('/about', (req, res) => {
res.send('About Page');
});
module.exports = router;Then in
app.js:const indexRouter = require('./routes/index');
app.use('/', indexRouter);What Just Happened?
Your computer is now a web server. When you visit that URL your browser sends a request to your Express app. The app sees the request for the root path ('/') calls the route handler and sends back the response. This is the foundation of all web applications built with Express.
Two Minute Drill
- Create an
app.jsfile and write your first server. - Use
app.get()to define routes andres.send()to respond. app.listen()starts the server on a specified port; use environment variables for flexibility.- Organize your project with folders for static files routes and views.
- Use Express Router to separate route definitions into modules.
- Run
node app.jsand visithttp://localhost:3000to see your app!
Need more clarification?
Drop us an email at career@quipoinfotech.com
