Express is a popular web application framework for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features and tools. In this tutorial, we'll guide you through the basics of getting started with Express.
Install Node.js
Before you can start building with Express, you need to have Node.js installed on your system. You can download and install it from the official Node.js website.
Create a New Project
Once Node.js is installed, create a new directory for your project and navigate into it:
mkdir express-tutorial
cd express-tutorial
Initialize a new Node.js project by running:
npm init -y
This will create a package.json
file in your project directory.
Install Express
Install Express by running:
npm install express
Create Your First Express Application
Create a file named app.js
in your project directory and add the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Save the file and run it with Node.js:
node app.js
Now, you can open your web browser and visit http://localhost:3000
. You should see "Hello World!" displayed.
Handling Routes
Express makes it easy to handle different routes in your application. Here's an example of handling a GET request:
app.get('/about', (req, res) => {
res.send('About Us Page');
});
Now, when you navigate to http://localhost:3000/about
, you should see "About Us Page" displayed.
Using Middleware
Middleware is a function that has access to the request and response objects, as well as the next middleware function in the application’s request-response cycle. Here's an example of using middleware:
app.use((req, res, next) => {
console.log(`Request URL: ${req.originalUrl}`);
next();
});
This middleware function logs the request URL before passing control to the next middleware or route handler.
Static Files
Express can serve static files from a directory named public
. Place your static files (HTML, CSS, JavaScript, etc.) in the public
directory and they will be served automatically:
app.use(express.static('public'));
Now, when you navigate to http://localhost:3000/index.html
, Express will serve the index.html
file from the public
directory.
Deploying Your Application
Once you've built your application and tested it locally, you can deploy it to a server or a cloud platform like Heroku. Visit the Express website for more information on deploying your Express application.
For more resources and tutorials on Express, check out the Express documentation and the Express GitHub repository.
Read more about Node.js and explore other web development frameworks.