1.Setting Up Express.js for a Node.js Application
Express.js is a fast, lightweight, and unopinionated web framework for Node.js, making it an excellent choice for building server-side applications. It simplifies handling HTTP requests, routing, and middleware integration. In this guide, we’ll walk through the process of setting up Express.js in a Node.js application, creating a simple server, and demonstrating basic routes.
2. Initialize a New Node.js Project
1. Open a terminal or command prompt.
2. Create a new project directory:
mkdir my-express-app
cd my-express-app
3. Initialize a package.json file:
npm init -y
This generates a default package.json file that manages your project’s dependencies.
3. Install Express.js
To use Express, you need to install it via NPM:
npm install express
This command adds Express to your project and creates a node_modules folder along with a package-lock.json file.
4. Create a Basic Express Server
1. In the project directory, create a new file called app.js:
touch app.js
2. Open app.js and add the following code to create a simple server:
const express = require('express');
const app = express();
const PORT = 3000;
// Root Route
app.get('/', (req, res) => {
res.send('Welcome to your first Express.js app!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
5. Run the Server
To run your Express server, execute the following command in the terminal:
node app.js
You should see output like:
Server is running on http://localhost:3000
Open your browser and navigate to http://localhost:3000 to see the message "Welcome to your first Express.js app!"
6. Adding More Routes
Let's add additional routes to handle different HTTP methods. Update app.js as follows:
// About Route
app.get('/about', (req, res) => {
res.send('This is the About Page');
});
// Contact Route
app.post('/contact', (req, res) => {
res.send('Contact form submitted!');
});
7. Handling Errors Gracefully
Add a custom error-handling middleware to catch and display errors:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});