Node JS Setting up an Express application
Setting up an Express application involves creating a project, installing Express, and configuring your application to handle routes, middleware, and other server-related tasks. Here’s a step-by-step guide to setting up an Express.js application:
1. Install Node.js
Before setting up an Express application, ensure that Node.js and npm (Node Package Manager) are installed on your system. You can download and install Node.js from nodejs.org, which includes npm.
2. Initialize Your Project
Create a Project Directory
Create a new directory for your Express application:
mkdir my-express-app cd my-express-app
Initialize a New Node.js Project
Run
npm init
to create apackage.json
file. This file will keep track of your project's dependencies and metadata. You can use the-y
flag to accept default settings:npm init -y
3. Install Express
Install Express using npm:
npm install express
This command will add Express to your project’s dependencies and create a node_modules
directory where Express and other dependencies are stored.
4. Create Your Express Application
Create the Main Application File
Create a file named
app.js
(orserver.js
) in your project directory:touch app.js
Set Up a Basic Express Server
Open
app.js
in your code editor and add the following code to create a simple Express server:const express = require('express'); const app = express(); const port = 3000; // Define a route for the home page app.get('/', (req, res) => { res.send('Hello, world!'); }); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
const express = require('express');
: Import the Express module.const app = express();
: Create an instance of the Express application.app.get('/', (req, res) => { ... });
: Define a route for the root URL (/
) that responds with "Hello, world!".app.listen(port, () => { ... });
: Start the server and listen on port 3000.
5. Test Your Application
Run the Application
In your terminal, run the following command to start your Express server:
node app.js
You should see output like:
Server is running at http://localhost:3000
Access the Application
Open your web browser and navigate to
http://localhost:3000
. You should see "Hello, world!" displayed on the page.
6. Add More Routes
You can define additional routes to handle different HTTP requests and paths.
Example:
// Define a route for the '/about' path
app.get('/about', (req, res) => {
res.send('About page');
});
// Define a route with route parameters
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);
});
7. Use Middleware
Middleware functions are used to handle requests and responses. You can use built-in middleware or define your own.
Example:
// Built-in middleware to parse JSON bodies
app.use(express.json());
// Custom middleware to log request details
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware
});
8. Serve Static Files
You can use Express to serve static files (e.g., images, CSS, JavaScript) from a directory.
Example:
// Serve static files from the 'public' directory
app.use(express.static('public'));
Create a
public
directory:mkdir public
Add static files (e.g.,
index.html
,style.css
) to thepublic
directory.
9. Error Handling
Implement error-handling middleware to manage errors gracefully.
Example:
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
10. Set Up a View Engine
For rendering dynamic HTML pages, you can set up a templating engine such as EJS, Pug, or Handlebars.
Example with EJS:
Install EJS:
npm install ejs
Configure Express to use EJS:
app.set('view engine', 'ejs'); app.set('views', './views'); // Set the views directory
Create a view file
index.ejs
in theviews
directory:<!DOCTYPE html> <html> <head> <title>My App</title> </head> <body> <h1>Hello, <%= name %>!</h1> </body> </html>
Render the view in a route:
app.get('/', (req, res) => { res.render('index', { name: 'World' }); });
Summary
- Initialize: Create a new Node.js project and install Express.
- Set Up: Create your main application file and set up a basic server.
- Define Routes: Add routes to handle different HTTP requests.
- Use Middleware: Implement middleware for various tasks.
- Serve Static Files: Serve static assets from a directory.
- Error Handling: Implement error-handling middleware.
- View Engines: Use templating engines to render dynamic content.