Express Server Setup
Introduction
Express.js is a lightweight, fast web framework for Node.js that simplifies and streamlines server-side programming. Its potent capabilities and simplicity have made it one of the most common frameworks for creating online applications and APIs. We'll go over the fundamentals of managing routes and configuring a server using Express in this blog article.
Setting up an express server
In the previous post of the series, a major setback found while creating servers in node was that it was too lengthy and did not contribute to a good developer experience. Here comes Express which is a framework for simplifying the process. All the authentication, and business logic are present on the express server supported in the node environment.
Install and setup
To get started with Express, we need to have Node.js and npm (Node Package Manager) installed on our machine. Once you have these prerequisites, we can set up a basic Express server by following these steps:
Initialize a new Node.js project:
mkdir my-express-app cd my-express-app npm init -y
Install Express:
npm install express
Create a basic server:
import express from"express" const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
Now, run the server using it, and we should see "Hello World!" when we visit http://localhost:3000
in our browser.
Handling Routes
Understanding Routes in Express
Routes define the endpoints of our application and specify how it responds to client requests. Express uses various HTTP methods like GET, POST, PUT, and DELETE to define routes. Here's a basic example:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.post('/contact', (req, res) => {
res.send('Contact Form Submitted');
});
Route Parameters and Query Strings
Express allows us to get values using route parameters and query strings. Route parameters are parts of the URL that we can capture using a colon (:
) before the parameter name.
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
app.get('/search', (req, res) => {
res.send(`Search Query: ${req.query.q}`);
});
In the first example, visiting /users/123
would display "User ID: 123". In the second, visiting /search?q=express
would display "Search Query: express".
This is all that I could cover today, building a server and handling routes in express. I am using Postman for testing the server requests which is a better and preferred way of testing the server.
That's it from my side, see you in the next article!