How to usequeries in Express
In this method, the URL parameter will be send in the URL as queries. Queries are appended at the end of actual url with a question character “?” appended at the last. Every query value will be mapped as key – value pairs and will be delimited with an ampersand “&” symbol.
http://example.com/api/?id=101&name=ragul
In the above example the queries are passed like below key – value pairs
Key |
Value |
---|---|
id |
101 |
name |
ragul |
Example: Using queries:
- To use URL parameters in type of queries, use the “req.query” property from request object in Express.
- Express will automatically add the queries from URL in the req.query as a Javascript Object.
Javascript
// server.js // create an express object const app = require( "express" )(); // server port const PORT = 8080; // using queries app.get( "/api" , (req, res) => { // get the URL parameters passed by // query with req.query const queries = req.query; res.send(queries); }); // listen for connections app.listen(PORT, () => { console.log(`server is listening at port:${PORT}`); }); |
- queries are being read from req.query and just simply returned as response.
Output:
How to handle URL parameters in Express ?
In this article, we will discuss how to handle URL parameters in Express. URL parameters are a way to send any data embedded within the URL sent to the server. In general, it is done in two different ways.
Table of Content
- Using queries
- Using Route parameter
Contact Us