Express.js is a popular web application framework for Node.js, making it easier to build web applications and APIs. This tutorial will guide you through the basics of using Express.js to create a simple web server.
Getting Started
Before you begin, make sure you have Node.js and npm installed on your machine. You can download and install Node.js from here.
Once Node.js is installed, you can create a new directory for your project and initialize it with npm:
mkdir express-tutorial
cd express-tutorial
npm init -y
Installing Express.js
Next, install Express.js by running the following command in your terminal:
npm install express
Creating a Basic Server
Now, create a file named server.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 running at http://localhost:${port}/`);
});
This code sets up a basic Express server that listens on port 3000 and responds with "Hello World!" when you navigate to http://localhost:3000/
in your browser.
Handling Routes
You can add additional routes to your server by using the app.get()
, app.post()
, app.put()
, app.delete()
, and other methods provided by Express.
For example, let's add a route that responds with a list of tutorials:
app.get('/tutorials', (req, res) => {
res.send([
'Express Basics',
'Middleware',
'Error Handling',
'Database Integration'
]);
});
Now, if you navigate to http://localhost:3000/tutorials
in your browser, you will see the list of tutorials.
Using Middleware
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. They can perform operations on the request and response objects, run some business logic, modify the next middleware, or terminate the request-response cycle.
Here's an example of a simple middleware function that logs the URL of every request:
app.use((req, res, next) => {
console.log(`Request URL: ${req.originalUrl}`);
next();
});
Error Handling
Express.js provides a way to handle errors in your application using error-handling middleware. You can define a middleware function that handles errors and respond with a custom error message and status code.
Here's an example of a simple error-handling middleware function:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Deploying Your Application
Once you have developed your Express.js application, you can deploy it to a web server or a cloud platform like Heroku. You can find more information about deploying Node.js applications here.
For more information on Express.js, check out the official documentation.