简体   繁体   中英

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

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%5B%24gte%5D=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%5B%24gte%5D=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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM