Queries Vs Params

Good morning.

I’ve been reading up on this topic, but I’m still not sure if I’m understanding this correctly.

Does the following code permit me to console {'name': eric}?

// req.query -> after ?
// req.params -> Can be written within url
app.get('/api/:date?name=bob', (req,res) => {
  console.log(req.query) // {name: bob}
}) 

I am aware I could easily test this on my own console, but it is not working for some reason.

You are confusing route parameters with query parameters.

If I want to pass a query parameter named 'name`, I would make the following request:

https://sitename.com/api?name=bob

bob would show up in the console by referencing req.query.name:

app.get('/api', (req,res) => {
  console.log(req.query.name) // bob
}); 

If I want to instead use a route parameter, I could make the following request:

https://sitename.com/api/bob

bob would show up in the console by referencing req.params.name:

app.get('/api/:name', (req,res) => {
  console.log(req.params.name) // bob
}); 

Not sure what you mean by not working. Your Node console?

1 Like

Thank you for replying.

As I understand :date means I would use req.params.date to access the value at date. What I’m caught up on is I’m going to have to immediately use req.query because of the question mark (?). So, if I want to access ‘bob’, would I have to write this?:

req.param.date.query

But this looks very wrong.

No. What does the request look like you are trying to dissect?

/api/:date?name=bob

Let me break this up to explain my logic.

In order to access:
:date: I will need to write req.param.date

name=bob: I will need to write req.query.name

However, I cannot just write req.param.date.req.query.name

I’m confused on how to access bob, when I’m going to need to use both parameters AND queries. How can I even do this?

Regarding your previous comment:

I understand this, however if api was a parameter (so :api), how would I go about it?

You want to access two route parameters or one route parameter and one querystring parameter?

One route and one query string, I believe. In the example I used above. I want to access ‘bob’.

Essentially my question boils down to this. I have this path '/api/:date?name=bob', what code do I write to access bob.

I’m sorry if I’m not making sense, this is pretty confusing to me and I appreciate your patience.

I you want to access a date as a route parameter and a name as a query parameter, then you could make a request to:

https://yoursite.com/api/2022-08-01?name=bob 

and use the following route to display the date and the name:

app.get('/api/:date', (req,res) => {
  console.log(req.params.date) // 2022-08-01
  console.log(req.query.name) // bob
});