Creating Your First Express Server
Building a server with Express is a straightforward process that allows you to handle incoming requests and send responses. This tutorial will guide you through creating a basic Express server, defining routes, and responding to client requests. By the end, you'll have a functioning server that can serve as a foundation for your RESTful API.
Setting Up the Express Server
Step 1: Install Express
If you haven’t done so already, navigate to your project directory in the terminal and ensure Express is installed. Run the following command:
npm install express
Step 2: Create the Server File
You should have a file named server.js
in your project directory. Open it in your code editor. If you don’t have this file yet, create it using:
touch server.js
Step 3: Basic Express Setup
Start by importing Express and creating an instance of it. Add the following code to your server.js
:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
This code imports the Express module, creates an application instance, and sets the port. The process.env.PORT
allows you to specify a port via environment variables, which is useful when deploying your application.
Step 4: Define a Simple Route
Routes are how you define the endpoints of your server. You can start by adding a simple route that responds with "Hello World!" when a user accesses the root URL. Add the following code to server.js
:
app.get('/', (req, res) => {
res.send('Hello World!');
});
This code sets up a GET route for the root URL. The req
object represents the incoming request, while the res
object is used to send a response.
Step 5: Start the Server
Now that you have your route defined, it's time to make the server listen for incoming requests. Add this code at the end of your server.js
file:
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This function tells your server to start listening on the specified port. When the server starts successfully, it logs a message to the console.
Step 6: Running Your Server
Open your terminal and run the following command from your project directory:
node server.js
If everything is set up correctly, you should see a message like:
Server is running on port 3000
Step 7: Testing the Server
Open a web browser or Postman and navigate to http://localhost:3000
. You should see "Hello World!" displayed on the screen. This confirms that your server is working and responding to requests.
Adding More Routes
Step 1: Define Additional Routes
Next, you can add more routes to your server. For example, you could create routes for different endpoints. Below, we'll define a few additional routes:
app.get('/about', (req, res) => {
res.send('About this API');
});
app.get('/contact', (req, res) => {
res.send('Contact us at [email protected]');
});
This code adds two new GET routes: /about
and /contact
. Each route sends back a simple string when accessed.
Step 2: Testing New Routes
After adding these routes, save the server.js
file and restart the server:
node server.js
Now, you can test the new endpoints by visiting http://localhost:3000/about
and http://localhost:3000/contact
in your browser or using Postman. Each URL should display the corresponding response.
Using Middleware
Middleware functions are a crucial part of Express applications. They can perform various tasks, such as logging requests, parsing request bodies, and handling errors.
Step 1: Using Built-in Middleware
Express comes with some built-in middleware that can be very helpful. One commonly used middleware is express.json()
, which parses incoming JSON requests. To use this middleware, add the following line right after creating your app instance:
app.use(express.json());
This line enables your server to parse JSON request bodies automatically. This is essential for handling data sent from clients in JSON format.
Step 2: Handling POST Requests
You can now create a new route that accepts POST requests. For example, add the following route to your server.js
:
app.post('/submit', (req, res) => {
const data = req.body; // Access the parsed JSON data
res.json({
message: 'Data received successfully!',
receivedData: data
});
});
This route listens for POST requests to /submit
. It responds with a confirmation message and includes the data that was sent.
Step 3: Testing the POST Route
To test the new POST route, you can use Postman:
- Open Postman and select "POST" from the dropdown.
- Enter
http://localhost:3000/submit
in the URL field. - In the "Body" tab, select "raw" and choose "JSON" from the dropdown.
- Enter some sample JSON data, like:
{
"name": "John Doe",
"email": "[email protected]"
}
- Click "Send."
You should receive a response confirming that the data was received, along with the data you sent.
Error Handling
Error handling is an essential part of any application. Express allows you to define custom error-handling middleware.
Step 1: Creating an Error Handling Middleware
Add the following code to the end of your server.js
file to catch any errors that occur in your application:
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack trace
res.status(500).send('Something went wrong!');
});
This middleware function logs the error to the console and sends a 500 status response to the client.
Step 2: Testing Error Handling
To test the error handling, you can create a route that purposely throws an error. Add this route to your server:
app.get('/error', (req, res) => {
throw new Error('This is a test error!');
});
Visit http://localhost:3000/error
in your browser. You should see the message "Something went wrong!" indicating that the error was caught by your error handling middleware.
Serving Static Files
In addition to handling API requests, Express can serve static files, such as images, CSS, and JavaScript files.
Step 1: Create a Public Directory
Create a directory named public
in your project folder. Inside this directory, you can place any static files you want to serve.
mkdir public
Step 2: Serve Static Files
To serve static files, you can use the built-in express.static
middleware. Add this line to your server.js
:
app.use(express.static('public'));
Step 3: Adding Static Files
Place a sample HTML file in the public
directory. For example, create a file named index.html
with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Static File Example</title>
</head>
<body>
<h1>Welcome to My Express Server!</h1>
<p>This is a static HTML page served by Express.</p>
</body>
</html>
Step 4: Accessing Static Files
With the static file server set up, you can now access your HTML file by navigating to http://localhost:3000/index.html
. The browser should render your HTML content.
Conclusion
You have successfully created your first Express server, defined multiple routes, implemented middleware, handled errors, and served static files. This foundational knowledge prepares you for more complex features as you develop your RESTful API. In the next tutorial, you will learn about CRUD operations and how to integrate a database into your application.