Express.js / Handling Requests and Responses

Reading Query Parameters and Form Data

This tutorial covers how to read query parameters and form data in Express. You will learn how to extract information from the URL and the form data sent by the user.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores working with request and response objects in Express.

Reading Query Parameters and Form Data in Express

1. Introduction

In this tutorial, you will learn how to extract and read query parameters and form data in Express.js, a popular web application framework for Node.js. Query parameters and form data are common ways to send information from the client to the server.

You will learn how to:
- Access query parameters from a URL
- Parse form data sent in a POST request.

Prerequisites:
- Basic knowledge of JavaScript
- Basic understanding of HTTP requests and responses
- Installed Node.js and Express.js on your computer

2. Step-by-Step Guide

Query Parameters

Query parameters are appended at the end of a URL after the question mark (?). Each parameter is separated by an ampersand (&). In Express, query parameters can be accessed using req.query.

Form Data

Form data are typically sent through HTTP POST requests. To handle these, Express needs to use middleware to parse the incoming request bodies. The middleware you'll use is called body-parser.

Best Practices and Tips

  • Always validate and sanitize incoming data to prevent security vulnerabilities.
  • Use appropriate status codes in your responses.

3. Code Examples

Reading Query Parameters

const express = require('express');
const app = express();
app.get('/search', function(req, res) {
  console.log(req.query); // logs the query parameters
  res.send('Received query parameters!');
});
app.listen(3000, function() {
  console.log('Server is listening on port 3000');
});

In this example, if you navigate to http://localhost:3000/search?name=John&age=20, you will see { name: 'John', age: '20' } logged in your console. req.query is an object containing the query parameters.

Reading Form Data

First, install the body-parser middleware:

npm install body-parser

Then use it in your Express app:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/submit', function(req, res) {
  console.log(req.body); // logs the form data
  res.send('Received form data!');
});

app.listen(3000, function() {
  console.log('Server is listening on port 3000');
});

In this example, if you submit a form to http://localhost:3000/submit with the fields name=John and age=20, you will see { name: 'John', age: '20' } logged in your console. req.body is an object containing the form data.

4. Summary

In this tutorial, you learned how to read query parameters and form data in Express.js. You were introduced to the req.query and req.body objects, which are used to access this data.

Further learning should include:
- How to handle different types of requests (e.g., GET, POST, PUT, DELETE)
- How to send responses back to the client
- More about Express middleware

5. Practice Exercises

  1. Create a route that accepts query parameters and returns them in the response body.
  2. Create a route that accepts form data and logs it to the console.
  3. Create a route that accepts form data, validates it (e.g., checks if a required field is present), and sends a response based on the validation result.

Solutions

// Exercise 1
app.get('/params', function(req, res) {
  res.send(req.query);
});

// Exercise 2
app.post('/log', function(req, res) {
  console.log(req.body);
  res.send('Logged form data!');
});

// Exercise 3
app.post('/validate', function(req, res) {
  if (!req.body.name) {
    res.status(400).send('Missing name field!');
  } else {
    res.send('Validation successful!');
  }
});

Remember to practice regularly and build on what you've learned here to improve your web development skills.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help