Table of Contents
Welcome to the comprehensive guide on getting started with Express.js, a popular web application framework for Node.js. Whether you're a beginner or looking to solidify your foundational knowledge, this tutorial will walk you through building your first web app with practical, easy-to-follow steps.
What Is Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It simplifies the process of building server-side applications by offering a straightforward API and middleware support.
Prerequisites
- Basic understanding of JavaScript and Node.js
- Node.js installed on your computer (version 14 or higher recommended)
- A code editor such as Visual Studio Code
- Terminal or command prompt access
Setting Up Your Project
First, create a new directory for your project and initialize a new Node.js project:
mkdir my-express-app
cd my-express-app
npm init -y
Next, install Express.js using npm:
npm install express
Creating Your First Express Server
Create a new file named app.js in your project directory and add the following code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Save the file and start your server by running:
node app.js
Open your browser and navigate to http://localhost:3000. You should see the message "Hello, World!".
Adding More Routes
Expand your app by adding more routes to handle different URLs. For example, add the following code to app.js:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
Now, visiting http://localhost:3000/about or http://localhost:3000/contact will display the respective messages.
Handling POST Requests
To handle form submissions or other POST requests, you'll need to use middleware like express.json(). Here's an example:
app.use(express.json());
app.post('/submit', (req, res) => {
const data = req.body;
res.send(`Received data: ${JSON.stringify(data)}`);
});
Test this endpoint using tools like Postman or curl by sending a JSON payload.
Deploying Your App
Once your app is ready, consider deploying it to cloud platforms like Heroku, Vercel, or DigitalOcean. These services provide straightforward deployment options for Node.js applications.
Conclusion
Getting started with Express.js is simple and efficient. With just a few lines of code, you can build scalable web applications. Keep exploring middleware, templating engines, and database integrations to enhance your app's functionality.
Happy coding!