--- 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> ![Ironhack Logo](https://i.imgur.com/1QgrNNw.png) # Express | POST Method - Request Body ## Learning Goals After this lesson you will be able to: - Send data from the browser to the server using `POST` requests - Understand and use FORM params throug `req.body` - Access this data in the server through `req.body` - Understand what **Middlewares** are and implement them. - Create your own Middlewares. ## Introduction :::info lecture Nous avons vu comment un navigateur allait pouvoir Ă©mettre des requĂȘtes `GET` : - saisie d'une nouvelle adresse dans la barre d'adresse - soumission d'un formulaire - lien - `<img src="">`, `<link href="">`, `<script src="">` --- Nous allons voir qu'il existe un autre type de requĂȘtes : les requĂȘtes `POST`... ::: 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 to send data from the browser to the server, and how the server receives those parameters and uses them to perform operations. ### Introduction to POST :::info lecture Nous avons Ă©galement vu que l'on pouvait passer des paramĂštres Ă  une requĂȘte GET : - en route params - en query params ::: When we navigate, we continuously make requests from the browser to the server. Most of the requests will be GET requests (i.e. give me this HTML/CSS/images)... but sometimes we need to send data to the server: - Creating a user account - Adding a new tweet - Updating your LinkedIn profile These actions have something in common: **they send data to create or update resources on the server.** HTML gives us two ways in which we can perform requests: GET and POST. :::info Actually, HTTP defines several request methods but in the browser, without the use of Javascript, we can only use two of them: GET and POST. When we request a resource (http://example.com/image.png), the browser performs a GET request to the server with that URL. We can send some information via the query string at the end of the URL (https://dummyimage.com/200x300?text=sent-via-query-string) but the amount and complexity of the data we can send via this method is very limited. To send more information, or to prevent the information from showing in the browser address bar and being stored in the browser history, we need to use html forms to send the data in the body of a POST request. ::: When we request a resource (http://example.com/image.png), it will implicitly create a GET request to the server with that URL. Nonetheless, we are not sending any information here. To send the information we typically need to use [html forms](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form). Let's look at an example: :::info lecture Si nous reprenons l'exemple d'un formulaire : ::: ```htmlmixed= <!-- Simple form which will send a GET request --> <form action="example.com/user-data"> <label for="first-name-input">First Name:</label> <input id="first-name-input" type="text" name="firstName"> <input type="submit" value="Save Name"> </form> ``` If we type `john` in the input field and submit this form, the browser will generate a new request to: :::info lecture Sa soumission provoque un changement de page (requĂȘte GET) vers : ::: ``` http://example.com/user-data?firstName=john ``` And then the server will be able to identify the route `/user-data` and extract all the parameters sent after the `?`, such as `firstName=john` in the above example. :::info lecture Nous voyons donc en clair la valeur saisie par l'utilisateur dans le champ : `firstname=John` => LIMITATIONS : - probleme de confidentialitĂ© si mot de passe (en clair ET dans l'historique) - quid si nous voulons passer une image en paramĂštre ? ::: This approach works and is sometimes useful, but there are two main problems/limitations with using GET: 1. We can't send large parameters with GET (like a photo for example). 2. Sensitive information (passwords) will be stored in your browser history and be visible. Because of this, POST was invented as an alternative method of sending data to the server: :::info lecture Pour lever ses limitations, une autre `method="POST"` existe, qui ne rĂ©vĂšlera elle pas les paramĂštres dans l'URL : ::: ```htmlmixed= <!-- Simple form which will send a POST request --> <form action="example.com/user-data" method="post"> <label for="first-name-input">First Name:</label> <input id="first-name-input" type="text" name="firstName"> <input type="submit" value="Save Name"> </form> ``` If we add `john` in the input field and submit this form, the browser will generate a new request to: :::info lecture Une fois le formulaire soumis, l'URL sera simplement : ::: ``` http://example.com/user-data ``` This time, `firstName=john` won't be in the URL, but instead, the browser will add (under the hood) all the form parameters as part of the HTTP request we send to the server. In this lesson, we are going to practice sending both GET and POST parameters from HTML, how to receive them in the server and send a response back. But before we get into it, let's look at a few differences between GET and POST: | FEATURE | GET | POST |:--------:|-----|-------- | **HTTP Method** | Corresponds to [HTTP GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) verb | Corresponds to [HTTP POST](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5) verb | **When to use** | Fetching resources | Updating data | **Form method** | `<form method="get">` (<b>by default</b>) | `<form method="post">` | **Form data** | Fields appended to the action URL with a '?' (query string) | Fields included in the body of the form and sent to the server | **History** | Parameters remain in browser history because they are part of the URL | Parameters are not saved in browser history | **Bookmarked** | Can be bookmarked | Can not be bookmarked | **Privacy Concerns** |GET method should not be used when sending passwords or other sensitive information | POST method used when sending passwords or other sensitive information | **Visibility** | GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send |POST method variables are not displayed in the URL <div class="skip"> ## Parameters (Params) ### Query String Parameters | A Form with `GET` As discussed previously, when we create a form, by default it does a `GET`, and adds the parameters to our URL, as so: ```htmlmixed= <!-- Simple form which will send a GET request --> <form action="example.com/user-data"> <label for="first-name-input">First Name:</label> <input id="first-name-input" type="text" name="firstName"> <input type="submit" value="Save Name"> </form> ``` ``` http://example.com/user-data?name=john ``` Let's create a form of our own. Our task is to gather our user's information and display it on another page. For now, we'll get their name, age, and favorite superhero. #### Step 1 | Display a Form First, we need a route to display a new view. We'll call this one `get-user-info`: ```javascript /* app.js */ app.get('/get-user-info', (req, res) => { res.render('user-info-form'); }); ``` Then, we must create a view called `user-info-form`: `$ touch views/user-info-form.hbs` And display the form, with all of its fields: ```htmlmixed <!-- user-info-form.hbs --> <form action="/display-user-info"> <label for="name-input">Name</label> <input id="name-input" type="text" name="name"> <label for="age-input">Age</label> <input id="age-input" type="number" name="age"> <label for="superhero-input">Favorite Superhero</label> <input id="superhero-input" type="text" name="superhero"> <button type="submit">Submit Info!</button> </form> ``` :::info :bulb: Either `<button type="submit">` or `<input type="submit">` can be used as submit buttons. ::: ##### input `type` The input `type` attribute lets the form know what the input is going to be. **All values will be sent as a string**, but the `type` can change how some inputs look. All input types can be found [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) on MDN. ##### input `id` The `id` attribute is on the label. The label `for` is attached to the `id` of the input. :::info :zap: This makes it so that if you click the label, the input will be focused. ::: ##### input `name` The `name` is the most important attribute in your input. This is how we send information from the form to the server. More on this in a bit. #### Step 2 | Use the `Query Params` The form is making a `GET` request to a route called `display-user-info`, so we have to create a route to handle that information and do something with it. ```javascript app.get('/display-user-info', (req, res) => { }); ``` Then, we can access the information through `req.query`: ```javascript app.get('/display-user-info', (req, res) => { let name = req.query.name; let age = req.query.age; let superhero = req.query.superhero; res.send(` Your name is ${name} Your age is ${age} Your favorite superhero is ${superhero} `) }); ``` What happened? Our form took all of our input fields and added them as `query parameters`. ![](https://i.imgur.com/kDXpTya.png) That means we can then access that data on the route that is receiving the request on the server. But what happens when we have sensitive information that we don't want to be displayed in the URL bar, or easily manipulated by the user? </div> ### Form Params | Making our first `POST` :::info lecture CrĂ©ons un formulaire de login... ```shell $ mkdir post-login $ npm init --yes $ npm install express hbs $ mkdir views $ touch app.js $ code . ``` ```javascript= const express = require('express'); const app = express(); const hbs = require('hbs'); app.set('views', __dirname + '/views'); app.set('view engine', 'hbs'); // TODO app.listen(3000, () => console.log('App listening on port 3000!')); ``` ::: Let's create our first `POST` request. Often with a `POST` request, our flow will look like this: ```flow st=>start: Show the user a form op=>operation: User types login info into form op2=>operation: User hits enter op3=>operation: Form does POST request op4=>operation: Server tries to login User op4=>operation: User is redirected (to a home page, newsfeed, etc) e=>end: End st->op->op2->op3->op4->end ``` #### Step 1 | Display a Form Let's create a new route, this will display a form to the user: :::info lecture CrĂ©ons notre **route pour l'affichage** du formulaire : ::: ```javascript=6 // app.js app.get('/login', (req, res) => { res.render('login') }); ``` As you noticed, we're rendering `login`. Create `login.hbs`: ``` $ touch views/login.hbs ``` And inside of `login.hbs`, let's create our first form: :::info lecture Et **notre vue** (aka. template) `views/login.hbs` : ::: ```htmlmixed <!-- views/login.hbs --> <form action="/login" method="POST"> <label for="email">Email</label> <input id="email" type="text" name="email"> <label for="password">Password</label> <input id="password" type="password" name="password"> <button type="submit"> Login </button> </form> ``` The *method* is what tells our form to make a `POST` request. When we're creating a login form, or submitting some information, we should always use a `POST`. This prevents the user from resubmitting information and is proper semantics. :::info lecture Si l'on soumet le formulaire : 404... ::: Click submit. What happens? #### Step 2 | `POST` route :::info lecture La route `/login` existe pour `GET` mais pas pour `POST`... Ajoutons cette route : ::: In the previous example, we get a 404 because we don't have a route with a method of `POST` and an action of `/login`. Let's create it! ```javascript=10 // app.js app.post('/login', (req, res) => { res.send("You've logged in!"); }); ``` Wait for a second...we never actually logged in! How do we access the information the user entered in the form on the server? ##### The Request Body / Parameters :::info lecture Nous nous sommes pour l'instant contentĂ©s d'afficher le message `"You've logged in!"`. Mais **comment allons-nous rĂ©cupĂ©rer les donnĂ©es saisies dans le formulaire** pour cette fois-ci pouvoir rĂ©ellement enregistrer notre utilisateur ? ::: `req` contains information about the request, including the email and password that the user entered into the form. Unfortunately, this data isn't readable by default in Express with a `POST` request. *Enter, [`bodyParser`](https://github.com/expressjs/body-parser)*! First, install `body-parser`: :::info lecture Afin de rĂ©cupĂ©rer les donnĂ©es `POST`Ă©es via le formulaire, nous allons utiliser un package `body-parser` : ::: ``` $ npm install body-parser ``` Then, add it to our app: :::info lecture Que nous **initialisons** maintenant dans `app.js` : ::: ```javascript // app.js ... const bodyParser = require('body-parser'); ... app.use(bodyParser.urlencoded({ extended: true })); ``` <div class="skip"> Body parser does just that. It parses the body of our request, and gives it to us in the `req.body`: ```javascript app.post('/login', (req, res) => { res.send(req.body); }); ``` Now we have a plain old JavaScript object to interact with! </div> :::info lecture Ainsi, nous pouvons maintenant avoir accĂšs aux valeurs saisies dans le formulaire, grĂące Ă  `req.body` : ::: ```javascript app.post('/login', (req, res) => { let email = req.body.email; let password = req.body.password; res.send(`Email: ${email}, Password: ${password}`); }); ``` What happened here? Our form sends its data in the request body to the server.`bodyParser` catches it, and turns it into a JavaScript object for us: :::success lecture Remarquons le lien entre `name=""` de chq champ et du l'entrĂ©e dans `req.body` ::: ![](https://i.imgur.com/lS3106c.png) **Exercise** :::info lecture <span style="font-size:500%">đŸ‹đŸœâ€â™€ïž</span> Ajoutons la logique nĂ©cessaire au login : - mail doit etre `ironhacker@gmail.com` - mot de passe doit etre `password` ::: Add some logic to the `post` route. If the email is `ironhacker@gmail.com` and the password is `password`, display a message saying "Welcome", otherwise display a message saying "Go Away". **Starter Code** ```javascript app.post('/login', (req, res) => { // What ES6 feature could we use to clean these two lines up? let email = req.body.email; let password = req.body.password; if (/* fill in this condition*/){ // render "Welcome" } else { // render go away } }); ``` ## Middleware When a request is made to our Express server, it doesn't actually go straight to the route. Often times, our route is actually the last stop. We've used a couple of packages thusfar, including bodyParser. These packages are called *Middleware*. >The term middleware is used to describe separate products that serve as the glue between two applications. > >Middleware is sometimes called plumbing because it connects two sides of an application and passes data between them. In this case, the two sides of the application consist of (1) the client making a request, and (2) the server handling that request. The following diagram illustrates how our application actually handles a request. ![Express App Requests](https://i.imgur.com/AO6lw3m.png) 1. The request passes through `cookieParser` 2. The request passes through `bodyParser` 3. The request passes through `logger` 4. The request passes through `authentication` 5. Finally, our request actually hits our route, and callback for it How does this work? Let's create a simple example to illustrate this. First, let's create a test route: ```javascript app.get('/test', (req, res) => { res.send("We made it to test!"); }); ``` Then, let's create a middleware of our own: ```javascript // ... app.use(myFakeMiddleware) // ... function myFakeMiddleware(){ console.log("myFakeMiddleware was called!"); } ``` Make a request to `localhost:3000/test`: ![](https://i.imgur.com/Lnqfi8P.png) But our browser doesn't load anything! Why? ### Middleware Pattern `app.use()` is a function that adds a middleware to our stack. All of the middlewares are called, one after the other, finally ending with your route. The problem is that we're not calling our next middleware. The chain is broken, and there is a clog in the pipe. Functions that work as middlewares receive 2-4 arguments and one of them is always the *next* middleware to call. Let's add that to our function: ```javascript function myFakeMiddleware(_, _, next){ console.log("myFakeMiddleware was called!"); next(); } ``` :::info :bulb: We'll discuss the first two arguments shortly! ::: We pass `next` as our third argument, then whenever our middleware is done logging, we call it. Visit `localhost:3000/test`. #### Passing Information Unless we're simply logging the request, often times we will need to pass information through our middleware. Express suggests attaching any of your data to the `request` object. This will then be available in every middleware, and in your route. Let's take a look at this example of a fake middleware: ```javascript function myFakeMiddleware(req, _, next){ console.log("myFakeMiddleware was called!"); req.secretValue = "swordfish"; next(); } ``` After our `myFakeMiddleware` middleware is called, we can easily access the *modified request* object. In this example, we can access `secretValue`: ```javascript app.get('/test', (req, res) => { let mySecret = req.secretValue; res.send(mySecret); }); ``` Often times we won't be designing a middleware of our own, Express already has a [huge ecosystem of middlewares](https://expressjs.com/en/resources/middleware.html), but it is quite helpful to understand how the request is processed. Let's talk about some extremely useful Node packages (some of which are middlewares) that will help you when developing apps. ## Final Notes Notice our `GET` and `POST` both have the same route name, `/login`. This is ok because the **verb** makes them *two completely different routes*. When we make the `GET` request, a form will be displayed. When the form makes a `POST` request, it will be sent to do login logic. ## Summary Sending data to the server is going to be one of the most common tasks in your web development journey. We discussed the three ways to do this through: - Query Parameters - Form data We talked a bit about how to handle the information server side as well through: - `req.query` - `req.body` Each of which are simple objects containing the data that a User submitted. We will have different use cases for each of the ways to send data from the client to the server, all of which will be highlighted as we progress. ## Extra Resources - [body-parser Docs](https://github.com/expressjs/body-parser) - [Anatomy of an HTTP request in Node](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/)