How do you retrieve the query string attached to a GET request URL path using Express.js and Node.js?

The query in any GET request URL path is the text behind the question mark ("?").

An example of what these URLs look like:

    
      /getUsers?userId=12354411
    
  

And a URL path can have more than one query parameter by adding a & symbol between each one:

    
      /getUsers?userId=12354411&name=Billy
    
  

When using Express, you can retrieve those URL parameters with this code:

    
      const express = require("express")

      const app = express()

      app.get("/getUsers", (req, res) => {
        const reqQueryObject = req.query // returns object with all parameters
        const userId = req.query.userId // returns "12354411"
        const name = req.query.name // returns "Billy"
      })
    
  

Express populates a req.query object that you can use directly in your routes that is filled with each parameter from the URL.

Notice in the code above that you can access the object with req.query. And that each individual URL parameter can be accessed with req.query.userId, req.query.name, etc.

If there aren't any query parameters attached to the URL, the req.query object will be empty.

Hopefully this was helpful in your coding endeavors.

Thanks for reading and happy coding!