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
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 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
.
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.
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.
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
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.