--- tags: ironhack, lecture, --- <style> .markdown-body img[src$=".png"] {background-color:transparent;} .alert-info.lecture, .alert-success.lecture, .alert-warning.lecture, .alert-danger.lecture { box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px; position:relative; ddisplay:none; } .alert-info.lecture:before, .alert-success.lecture:before, .alert-warning.lecture:before, .alert-danger.lecture:before { content:"👨‍🏫\A"; white-space:pre-line; display:block;margin-bottom:.5em; /*position:absolute; right:0; top:0; margin:3px;margin-right:7px;*/ } b { --color:yellow; font-weight:500; background:var(--color); box-shadow:0 0 0 .35em var(--color),0 0 0 .35em; } .skip { opacity:.4; } </style> ![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) # Express | GET Methods - Route Params & Query String ## Learning Goals After this lesson you will be able to: - Understand how GET methods works - Learn how to send data from the browser to the server - Learn how Route Params works - Learn how Query Strings works - Understand the difference between route and query params ## Introduction :::info lecture Dans un navigateur lorsque dans la barre d'adresse nous accédons à une URL : **c'est une requête `GET` qui est émise**. Voyons cela aujourd'hui de manière plus détaillée... ::: Simple web applications are a one-way communication from the browser to the server. The browser emits a request, and the server sends back a resource (HTML, CSS, JS), this is what we call `GET` requests. You can think of `GET` requests as an HTTP request where you want to *get* something. In this lesson, we are going to learn how also to send data from the browser to the server, and how the server receives those parameters and uses them to perform operations. ## Set the environment :::info lecture setup ::: For this learning we are going to need an app to practice all the concepts, go ahead and create a folder `express-get-params` and an `app.js` file inside it. We will also need some **node modules**, so you should run the `npm init` command. After creating the `app.js` we need the `views` directory and an `index.hbs` file inside. ```shell $ mkdir express-get-params $ cd express-get-params $ npm init --yes $ touch app.js $ mkdir views; $ touch views/index.hbs $ code . ``` :::info lecture N'oublions pas non plus d'installer les packages : ::: On the `app.js` file, copy/paste the following code, and install the `express`, `path` and `hbs` modules using : ```shell $ npm install express hbs ``` ```javascript // app.js const express = require('express'); const app = express(); const hbs = require('hbs'); app.set('views', __dirname + '/views'); app.set('view engine', 'hbs'); app.get('/', function (req, res) { console.log(req); }) app.listen(3000, () => console.log('App listening on port 3000!')); ``` :::info lecture Astuce, on peut définir des commandes dans la section `"scripts"` de `package.json`, par ex ici: `npm start` ::: And finally, let's add `nodemon`, so we do not need to restart the server for every change. On the `package.json` file, add the following line inside the **scripts** object: ```json "start": "nodemon app.js", ``` The package.json should look like this: ```json { "name": "get-params", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.16.2", "hbs": "~4.0.1" } } ``` :::info The version may not be the same! Don't worry about that! ::: :::info lecture Démarrons notre serveur ! ::: We are ready! Go to the terminal and run the **`npm start`** command. You should see the following: ![image](https://user-images.githubusercontent.com/23629340/34479960-d22f6f0c-efa9-11e7-9ae2-484a1ed2b784.png) Our server is up and running! ## GET Request :::info lecture Nous allons avoir **2 façons de "passer" des données** à notre serveur depuis le navigateur lors d'une requête GET : ::: Every time we navigate to an URL, we are making a GET request to the server, and there are some ways we can send data to our server to use that info. We will learn two techniques of delivering data to our server through GET requests: - Route Params - Query Params ### Route Params :::info lecture ``` /users/:username -> req.params.username ``` ::: Route parameters are **named URL segments** that are used to capture the values specified at their position in the URL. The obtained values are populated in the **req.params** object, with the name of the route parameter specified in the path as **their respective keys**. To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. Let's add the following code to our `app.js` file: ```javascript app.get('/users/:username', (req, res, next) => { res.send(req.params); }) ``` Let's navigate to **`http://localhost:3000/users/ironhack`** on our browser! ![image](https://user-images.githubusercontent.com/23629340/34480090-b237a754-efaa-11e7-8cae-5b1e50e5b1b8.png) :::info lecture C'est à nous de nommer les params ! ::: Notice that the `:username` is populated on the **req.params** Object as a `key` and the `string` we send on that position of the URL is the `value` of that `key`. That means that we can replace the `:username` with anything we want. For example, let's receive a `bookId` this time: ```javascript app.get('/books/:bookId', (req, res, next) => { res.send(req.params); }) ``` Let's navigate to **`http://localhost:3000/books/131l2kj3h$j3h1jk2`** on our browser! ![image](https://user-images.githubusercontent.com/23629340/34480250-9511294c-efab-11e7-9cb3-e8186435b00e.png) #### More Route Params Sometime we will need to send more than one parameter, in those cases we can do something like the following: :::info lecture Ça marche aussi avec plusieurs params : ::: ```javascript app.get('/users/:username/books/:bookId', (req, res, next) => { res.send(req.params) }) ``` So, if now we navigate to **`http://localhost:3000/users/ironhack/books/8989`** on our browser, we should see the following: ![image](https://user-images.githubusercontent.com/23629340/34480049-67c173a8-efaa-11e7-8351-d5f1868a534f.png) #### Examples :::info lecture Exemple avec github utilisant les params d'URL : ![](https://i.imgur.com/FZxMXAE.png) ::: Navigate to [Ironhack Labs Github Account](https://github.com/ironhack-labs) and check the URL. **How you think is Github server getting the info on which profile they should display? Have they one route for each repository? Or maybe something like this?** ```javascript app.get('/:repository', (req, res, next) => { //............ }) ``` :::success Parameterized routes are handy for developing an app because it allows us to get info from clients requests and displaying info according to that info! ::: ### Query String :::info lecture ``` /search?city=Paris -> req.query.city ``` ::: Sometimes we will find useful to send params on the URL as a string, and for that purpose Query Params are fantastic. In simple terms, the **query string** is the part of a URL after the question mark `?` and usually contains key value pairs separated by `&` and `=`. These **key/value** pairs can be used by the server as arguments to query a database, or maybe to filter results. You will receive the info on the `req.query` object of our routes. Let's check an example: Add the following code on the `app.js` file: :::info lecture Exemple à tester : ::: ```javascript app.get('/search', (req, res, next) => { res.send(req.query) }) ``` Same as route params, **query params** are key-value pairs object. Everything that comes after the `?` it's going to be pair as key-value using the `=` as a separator. Go ahead and navigate to **`http://localhost:3000/search?city=Barcelona`** So in our case we will have: ```javascript console.log(req.query); // => { "city" : "Barcelona" } ``` :::warning It's super important to notice the difference between **route params** and **query strings**. On query strings, the URL we create on the `app.js` does not include the params. ::: #### More Query String :::info lecture Si plusieurs query-params : ``` /search?city=Paris&country=FR ``` ::: When we are doing some searches or filters, is common to have more info to send to the server. In that case, we can use the `&` to attach more params. If we want to add a `start-date` for example, let's navigate to **`http://localhost:3000/search?city=Barcelona&start-date=2018-01-18`** ```javascript { "city" : "Barcelona", "start-date" : "2018-01-18" } ``` #### Query String from Forms :::info lecture Cas des formulaires... ::: Super-frequent use for the `query string` is to use them when sending info from a form, for example, a user search. Let's imagine we are doing an app where the users can search for Hotel Rooms to rent in different cities. In our `app.js` let's add the following code: :::info lecture Rendons un formulaire de recherche dans `index.hbs` sur la route `/`: ::: ```javascript app.get('/', (req, res, next) => { res.render('index'); }) ``` And on our `index.hbs` file, add the following: ```html <form action="/search" method="GET"> <label> City <input type="text" name="city"> </label> <label> Start-Date <input type="date" name="start-date"> </label> <label> End-Date <input type="date" name="end-date"> </label> <button type="submit">SEARCH</button> </form> ``` :::success Wait for a second! Let's review some key stuff about our code: - The `form` method is **GET**. By <b>default, it will always be a **GET**</b> method. - The `form` action is **/search**, means that when we click on the **SEARCH** button, we will make a **GET request to `/search` route** - On each input, what we put in the `name` field will be each of the `keys` on the `req.query` object, and what's on the input will be the `value`. ::: So, let's navigate to **`http://localhost:3000`** , complete the form and click on the **SEARCH** button. We should see something like this: ![image](https://user-images.githubusercontent.com/23629340/34487485-d2334930-efd4-11e7-8be9-252113e0246a.png) Awesome huh? ### Examples :::info lecture Essayons sur https://github.com/search : ![](https://i.imgur.com/q6FnRan.png) ::: Let's try it on real-world apps so we can see how they work. Navigate to [Github](www.github.com) and search for "ironhack" on the input displayed on the top bar: ![image](https://user-images.githubusercontent.com/23629340/34487650-8ee39f08-efd5-11e7-821c-52f999be6e85.png) When we search we notice the URL is the following: :::info https://github.com/search?utf8=✓&q=ironhack ::: ### Cheat Table :wink: :::info D'autres propriétés de `req`, cf: https://expressjs.com/fr/4x/api.html#req ::: Given the URL: `http://localhost:3000/products/1345?show=reviews`, and the route `/products/:id`, we can destructure the `req` object in the following fields: |HTTP Request | Express `req` object | value | |------------------|----------------------|-------| |Method | `req.method` |`GET`| |URL Path | `req.path` |`/products/1345`| |URL Params | `req.params.id` | `1345` | |URL Query String | `req.query.show` | `reviews` | |All headers | `req.headers['Accept-Language']` | `"en-US,en;q=0.9` | ### Route Params vs. Query Strings :::info lecture A votre avis : ::: Concepts must be more evident by now, especially knowing the difference between both **route** and **query** params, but for discussing a little more about the subject we list some examples, and you have to choose which approach will fit better: - Visit a user profile on Facebook - Search an apartment on Airbnb - See flights Madrid-Miami on 21-Oct on Skyscanner - Check news on CNN web page :::info lecture NB: SEO ::: ## Summary We learned how we could send info to the server using GET method. Using **route** params or **query** strings we should be able to pass all the info we need on our web apps. We also have seen the difference between both ways of passing the info, and how we need to structure our code to get that info on each of both approaches. ## Extra Resources - [Express Routing](http://expressjs.com/en/guide/routing.html) - [Express API](http://expressjs.com/en/api.html)