Skip to content
Advertisement

req.query returns nothing

Trying to get variable from http://localhost:3000/categories/subcategories?category_id=13 but req.query returns empty result.

app.get('/subcategories', (req, res) => {
 let category_id = req.query.category_id
 console.log(req.query)
 db.query('SELECT subcategory_name FROM subcategories WHERE category_id=(?)',
 [category_id],
 (err, result) =>{
   res.send({category_id})
 });
})

Is this possibly a problem with the way I’ve set up my server?

Advertisement

Answer

See how you are passing the data , directly entering the data or from another URL you are passing the data. Ensuring you are not sending data via req.body. Ref :

Empty req.query on ExpressJS

or check res.send({category_id}) . Try printing res.send({“category_id”: category_id}) . or see console.log(JSON.stringify(req.query))

Or Extract Query Parameters Without Express

const url = require('url');
const querystring = require('querystring');

let rawUrl = 'https://stackabuse.com/?page=2&limit=3';

let parsedUrl = url.parse(rawUrl);
let parsedQs = querystring.parse(parsedUrl.query);

https://stackabuse.com/get-query-strings-and-parameters-in-express-js/

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement