Antoine BERNIER
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- 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)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully