How to implement getting a get request for any number of different parameters?
Query string example:
/api/users/search?firstName=iv&lastName=cat /api/cars/search?color=red How to implement getting a get request for any number of different parameters?
Query string example:
/api/users/search?firstName=iv&lastName=cat /api/cars/search?color=red To access query query parameters in express, there is a built-in request.query object that contains the key-value pairs of these parameters. For example, for a query like / api / users / search? FirstName = iv & lastName = cat, it will look like this:
{ firstName: 'iv', lastName: 'cat', } If the request is sent without parameters, then an empty object will be stored in request.query.
Here is a small example of using the request.query object to dynamically generate a database query:
export const oldSetFilters = (filters: {[key: string]: string }): string => { let filtersString = ''; if ( filters && Object.keys(filters).length ) { for (const key in filters) { filtersString += `${ key }=${ filters[key] } AND `; } } filtersString = `WHERE ${filtersString.substring(0, filtersString.length - 5)}`; return filtersString; }; Handler route:
app.route('/v2/:table') .get( async (req, res) => { try { const filters = oldSetFilters(req.query); const rows = await db.sqlGetRequest( `SELECT * FROM ${req.params.table} ${filters};` ); logger.info(`${req.params.table} were sent to admin`); res.status(200).send(rows); } catch (error) { logger.error(`${req.params.table} sending to admin failed`, error); res.status(500).send(error); } }) Hope this helps.
filters in the first example? in the second example, where does the table in the logger come from? - MaxSource: https://ru.stackoverflow.com/questions/936749/
All Articles
router.get('/:instanceId', (req, res, next) => {});. In this example, theinstanceIdparameter. My gap is that I need one such handler to handle a get request in which there can be any number of parameters with different names. - Maxvar url = require('url'); var url_parts = url.parse(request.url, true); var query = url_parts.query;Code naguen per minute to enSO. - Vladimir Klykov