Introduction to Route and Query Parameters

Welcome to today's Express.js lesson about Route and Query Parameters. Both play pivotal roles in handling HTTP requests in web applications. Imagine sending a letter; the street address (Route Parameter) is essential, while "Attn: Tim" (Query Parameter) is optional. Now, let's dive into these exciting terms.

What are Route and Query Parameters?

In web requests, route parameters come directly in the URL, serving as "placeholders" for actual values — they guide the requests, much like a GPS guiding a vehicle. On the flip side, query parameters send extra, optional information. They come after a ? in a key=value format.

In the above URL, 123 and photos denote route parameters, while year=2021 implies a query parameter.

Adding and Using Route Parameters

In Express.js, we create Route Parameters in the path of the route using a colon :. Use req.params to fetch them in the route handler function:

In this example, /users/123 would output The user id is: 123.

Adding and Using Query Parameters

Query parameters are added after a ?. To access them, use req.query.

A request to /search?q=coding will give Search results for: coding.

Route Parameters vs Query Parameters

Route parameters are the must-have data; query parameters are the good-to-have bits. Route parameters are excellent for identifying data like IDs, and query parameters work well for optional user queries or preferences.

Putting It All Together

Let's merge these parameters in a mini application.

Here, /user/John will greet the user John with Hello, John!, while /search?q=nodejs will show You searched for: nodejs.

Lesson Summary and Practice

We've explored Route and Query Parameters in Express.js, essential for web development. Are you ready for practice exercises? The practice will strengthen your understanding, further cementing your skills in Route and Query Parameters. All the best!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal