Skip to main content

Command Palette

Search for a command to run...

url parameters vs query strings

Published
2 min readView as Markdown
URL ParametersQuery Strings
Part of the URL path itselfPart of the URL after a ?
Used to identify specific resourcesUsed to send extra information (filters, options, etc.)
Declared with a colon : in route pathDeclared by appending ?key=value pairs
Example: /user/:id/user/101Example: /products?category=shoes&sort=price
Accessed in Express using req.paramsAccessed in Express using req.query

How we can create routes with express js and how we can handle it?

Creating and Handling Routes in Express.js

Express.js is one of the most popular Node.js frameworks for building web applications and APIs. Its simplicity and flexibility make it an excellent choice for managing routes and handling HTTP requests. In this article, we’ll explore how to create and handle routes effectively in Express.js.

What are Routes?

Routes in Express.js define the pathways through which clients (such as browsers or other applications) can interact with your server. Each route maps to an HTTP method (like GET, POST, PUT, DELETE) and a URL endpoint.

Step-by-Step Guide to Creating Routes

1. Installing Express.js

To get started, you first need to install Express.js in your project. Use the following command:

npm install express

2. Setting up the Basic Server

const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse incoming JSON data
app.use(express.json());

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

3. Creating Routes

Routes specify how the server should respond to different types of HTTP requests. Below are examples for GET, POST, PUT, and DELETE methods:

GET Route

A GET route is used to retrieve data from the server.

app.get('/home', (req, res) => {
  res.send('Welcome to the Home Page!');
});

4. Dynamic Routes

Express supports dynamic routes where URL parameters can be passed:

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`Fetching details for user with ID: ${userId}`);
});