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.
Section overview
5 resourcesExplores 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
- Create a route that accepts query parameters and returns them in the response body.
- Create a route that accepts form data and logs it to the console.
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article