Home > database >  Getting `undefined` on res.query for a JSON query string using qs library
Getting `undefined` on res.query for a JSON query string using qs library

Time:01-21

I'm using qs to build JSON based query parameters to my REST API call:

On client side:

 import qs from "qs";
 
 let query = {
      dateTime: { $gte: 1664557995000 }
    };

let q = qs.stringify(query);

let url = "http://localhost:3000/testapi/events?"   q;

console.log(url) <<=== http://localhost:3000/testapi/events?dateTime[$gte]=1664557995000

let response = await fetch(url, {
method: "GET",
headers: new Headers({
    Accept: "application/json",
    "Content-Type": "application/json",
}),

On the server side I'm getting undefined on res.query:

app.get(
    "/testapi/events",
    async (req, res) => {
        
        console.log(res.query) <<=== undefined

        let query = qs.parse(res.query);

        console.log(query) <=== undefined
    }
)

I'm getting undefined for res.query and therefore I cannot parse it.

At the end, no parameters are being sent to the server.

I have no clue why is that happening, as the query string contains the parameters (dateTime[$gte]=1664557995000).

I need to rebuild the JSON on the server side to proceed to a mongo query. JSON types will involve even more complex parameters ($or, $and, etc).

CodePudding user response:

res is the response object. You receive the query on the req object - i.e., you should be using req.query, not res.query.

  • Related