7

I have a constant that uses the request query to pull into my API the name and town values of the URL parameters.

This works great. What I can't work out, I've looked at a number of articles but I want to return the full set of parameters from the URL, either as an array or a string. If it includes the URL path it's no problem, ideally just the parameters ampersand separated or any other way.

I need to do so as this API captures a set of question responses that may change over time, and I need the flexibility to loop over all the answers returned irrelevant if its 10 or 100.

export default async function (req, res) {
    const {
        query: name ,
        query: town ,
    } = req
    // ...
}
2
  • 1
    Not sure if I understood your question correctly, but don't you have access to req.url, which contains the full URL including the query params? Commented Jan 30, 2021 at 14:50
  • 1
    Thanks Juliomalves, I was looking for a reference of the properties on req, but all I found was numerous examples not the properties... if you post it, I'll mark it as the anwser. Commented Jan 30, 2021 at 14:53

1 Answer 1

9

You can access the query params as a string from req.url which contains the full URL including the query params.

export default async function (req, res) {
    console.log(req.url) // Logs: '/api/info?name=john&town=london'
}

For more details on the req object check Node.js official documentation.


Alternatively, you can also get the query params as an object from the req.query object, which you can manipulate however you like.

export default async function (req, res) {
    console.log(req.query) // Logs: { name: 'john', town: 'london' }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.