All language subtitles for 010 Processing Post Requests with Body Parser_en

af Afrikaans
ak Akan
sq Albanian
am Amharic
ar Arabic
hy Armenian
az Azerbaijani
eu Basque
be Belarusian
bem Bemba
bn Bengali
bh Bihari
bs Bosnian
br Breton
bg Bulgarian
km Cambodian
ca Catalan
ceb Cebuano
chr Cherokee
ny Chichewa
zh-CN Chinese (Simplified)
zh-TW Chinese (Traditional)
co Corsican
hr Croatian
cs Czech
da Danish
nl Dutch
en English
eo Esperanto
et Estonian
ee Ewe
fo Faroese
tl Filipino
fi Finnish
fr French Download
fy Frisian
gaa Ga
gl Galician
ka Georgian
de German
el Greek
gn Guarani
gu Gujarati
ht Haitian Creole
ha Hausa
haw Hawaiian
iw Hebrew
hi Hindi
hmn Hmong
hu Hungarian
is Icelandic
ig Igbo
id Indonesian
ia Interlingua
ga Irish
it Italian
ja Japanese
jw Javanese
kn Kannada
kk Kazakh
rw Kinyarwanda
rn Kirundi
kg Kongo
ko Korean
kri Krio (Sierra Leone)
ku Kurdish
ckb Kurdish (Soranî)
ky Kyrgyz
lo Laothian
la Latin
lv Latvian
ln Lingala
lt Lithuanian
loz Lozi
lg Luganda
ach Luo
lb Luxembourgish
mk Macedonian
mg Malagasy
ms Malay
ml Malayalam
mt Maltese
mi Maori
mr Marathi
mfe Mauritian Creole
mo Moldavian
mn Mongolian
my Myanmar (Burmese)
sr-ME Montenegrin
ne Nepali
pcm Nigerian Pidgin
nso Northern Sotho
no Norwegian
nn Norwegian (Nynorsk)
oc Occitan
or Oriya
om Oromo
ps Pashto
fa Persian
pl Polish
pt-BR Portuguese (Brazil)
pt Portuguese (Portugal)
pa Punjabi
qu Quechua
ro Romanian
rm Romansh
nyn Runyakitara
ru Russian
sm Samoan
gd Scots Gaelic
sr Serbian
sh Serbo-Croatian
st Sesotho
tn Setswana
crs Seychellois Creole
sn Shona
sd Sindhi
si Sinhalese
sk Slovak
sl Slovenian
so Somali
es Spanish
es-419 Spanish (Latin American)
su Sundanese
sw Swahili
sv Swedish
tg Tajik
ta Tamil
tt Tatar
te Telugu
th Thai
ti Tigrinya
to Tonga
lua Tshiluba
tum Tumbuka
tr Turkish
tk Turkmen
tw Twi
ug Uighur
uk Ukrainian
ur Urdu
uz Uzbek
vi Vietnamese
cy Welsh
wo Wolof
xh Xhosa
yi Yiddish
yo Yoruba
zu Zulu

Original subtitles

Now here's a question. What exactly happens when I press on this Calculate button?

Well currently, I've got my server running on port 3000, and I'm running my calculator.js file.

So if I go to Chrome, and I open up my Chrome Developer Tools, then I head over to the Network tab, and

make sure that down here you've got the All tab selected as well,

we're going to test our form out.

So I'm going to put in a first number and a second number, and then I'm going to press Calculate. Now

a whole bunch of things happen, and all of these networking requests get logged down here.

But we get this code 404, and everything's in red,

which seems kind of like it's bad,

and then we get this error up here saying, “Cannot POST to /index.html”.

Now where does that come from?

Well, if we have a look inside our index.html, then you can see that our form has an action and

a method.

Now the method is the post method,

so we're sending this data somewhere, and that somewhere is what's defined by the action attribute.

So we’re sending it to something called index.html,

which is not what we want. We want to send it to our server, which is at the home route location,

so it's just the forward slash.

Now, if you don't have an action attribute, that's fine as well. By default, if it doesn't exist, then the

form will simply send the data to the current page where it's on,

so that will be the equivalent of this.

But let's just have it in there for clarity’s sake.

So our form has a post method, which means it's going to try and send the data that is entered into the

inputs to a location that is our home route.

So now, if we hit save, and we go back to our localhost:3000, our home page, and let's try again pressing

that Calculate button.

Now this time, we're still getting a 404 and a “Cannot POST”,

but if you click on it, and you go over to the Headers tab, and you scroll down, you can see that we've

got a bunch of information, including some form data, and the data that we're getting access to is the

parameter num1, which remember is bound to our first input using the name attribute, and then that

has a value of 2, which is what we entered into the form previously, and the input with a name of num2

has a value of 3.

But we have a problem, because the status code is ‘404 Not Found’.

Now, you might have already come across the error code 404 while you're browsing web sites, and in fact

a lot of companies and web sites pride themselves on how they design their 404 site, and that just

goes to show how often this happens.

Now, if you're interested in a redacted but slightly rude version of how HTTP return codes work, then it's

basically if it's in the 100s it means hold on, something's going to happen,

the 200 means ‘here you go’,

this is usually a successful request code, 300 means go away,

there’s some security involved, 400s means you screwed up, 500s means I screwed up.

Now if you want to see the full list, then you can head over to trusty old Wikipedia, and you can see

a list of all of those status codes.

So the two most often codes you'll see is 200, which means everything was successful. 400s tend

to be client errors,

so the user who's using a browser to request something that doesn't exist, for example.

Well, what's actually going on in our case?

Well, the problem is that our server does not have a way of processing any post requests,

so we're basically not accepting anybody to post to our home route.

So let's go ahead and fix that.

Let's add an app.post method to handle any post requests that come to our home route, and then we're

going to have a callback with, again, req and res, request and response.

And we're just going to send back,

“Thanks for posting that!”

And then we're going to go back to our localhost:3000,

I'm going to put in two numbers and press Calculate.

You can see now, when we look at our localhost, we’re getting a message back,

and also we're getting the status code 200, which is ‘OK, everything's great, everything's working great.’

Now there's just one problem.

How do we tap into these pieces of form data? Because that's essentially what we need,

right?

We need to be able to get that data into here, into this callback function, so we can calculate the output,

and then send the result back to the browser.

Now, in order to tap into those pieces of data, we have to install another NPM package, which is called

Body Parser.

So let's head over to our command line, and Command C to exit our server, and then we're going to npm

install body-parser. And what this is going to do is it's going to allow us to pass the information

that we get sent from the post request.

So it might look something like this, a whole load of mumbojumbo data, and we're going to parse it so that

we have access to properties and variables, so we can do our calculations.

So now that we've installed body-parser and it's now inside our package.json as one of our dependencies,

we can head over to our calculator.js, we can require it, so that we incorporate that package into

our current project. So we can create a new const that's called bodyParser, and it's going to be requiring

body-parser package that we just installed.

So you can see that by naming constants, I'm still following the rules of how we named variables in Javascript,

namely camel casing.

But the actual package

I can't change,

and it's called body-parser.

So now that we've incorporated Body Parser into our project, the next step is to get our app to use it.

And Body Parser works with Express, so we can say app.use,

and we're going to specify the thing we wanted to use, which is bodyParser. Now Body Parser has a few modes,

if you will. There is, for example, bodyParser.text,

so parse all the requests into text, or bodyParser.json, which is that special format that we saw before,

which kind of looks a bit like Javascript objects, or the one that we're going to be using is

bodyParser.urlencoded.

And this is the special one that we use when we're trying to parse data that comes from an HTML form.

So whenever you're trying to grab the information that gets posted to your server from an HTML form, you're

going to be using urlencoded.

And in addition to that, we're going to add an option called ‘extended’, and we're going to set it to be

‘true’.

And by setting that extended option to true, that basically just allows us to post nested objects. And

it's not something that we're going to be using, but it's something that bodyParser is requiring you

to explicitly declare.

So this is basically the code that you need to write

every single time you want to use Body Parser.

Now why would you want to use Body Parser?

Well, it allows you to go into any of your routes, and you can tap into something called request.body,

and this is the parsed version of the HTTP request.

So let's go ahead and log this and see what we get when we try to make a post request.

So let's restart our server and reload our web site, and let's put in two numbers, 2 and 3, and I'm

going to hit Calculate.

So we get sent back,

“Thanks for posting that!” from the res.send,

but we also execute the console.log, where we log the request.body, and that logs in here as everything

that we saw over here, which is the form data.

So, by using Body Parser, we're able to parse the HTTP request that we get,

and by using urlencoded we can get access to the form data, and we can then tap into each of these

as if they were just properties of the object body.

So we can, for example, log request.body.num1. And remember that naming comes from the name

attribute of your input.

So now we're only logging the value of the first input.

So if we go back to our web site and put in a number in here, say 5 and 6,

then when we press Calculate, we get 5 logged in here,

so that value gets stored inside

this request.body.num1.

So now that we know how we can tap into these values, then making our calculator is super duper simple,

right?

All we need to do is create a variable that's going to hold our num1, and that's going to be equal

to request.body.num1.

And then we're going to create another one called num2, and this is going to be equal to

request.body.num2.

And then we can calculate the result, which is going to be num1

+ num2, which is making a really simple calculator that adds two numbers.

And then we're going to send back, instead of “Thanks for posting that!”, we'll say, “The result of the calculation

is “, and then we're going to append that variable result onto the end.

So now let's hit save,

update our server,

go over to our home page, and let's try and add 4 and 5 together,

press Calculate, the result of the calculation is 45.

So what's going on here?

Well, this num1 and num2 that we're getting back from bodyParser,

it gets parsed as text,

so if we want this to be a number, then we need to explicitly turn this into a number.

And, if you remember from earlier lessons on Javascript, we do that by simply writing Number, with a capital

N, and inside the parentheses we put in the piece of text that we want to turn into a number.

And so now, when we're calculating results, instead of appending num1 to num2, we can add num1

to num2.

So let's try this again.

The first number is 4, second number is 5.

And now we get 9.

So if you're wondering how we got these words num1 and num2, then it's as simple as going

into your index.html and changing the name here.

Let's call it n1 and n2 instead.

And now we can tap into it through n1 and n2.

So the body is everything that we got after we parsed the request,

and then the n1 is the value of the item in the form that has a name of n1.

So our web site still works exactly the same. 1 plus 2 is equal to 3.

And it's using these name attributes to grab the value inside that input, and then we're parsing that

information using request.body, we're turning it into a number, and we're adding the two numbers together

to get to send back the result.

So I've kept this project super duper simple, because there's a lot of other things going on, especially

using Body Parser, and getting hold of our post request through the post route, and it will take some time

for all of this to make sense.

But we're going to be doing plenty of repetition on this so that you really get it.

The important thing to take away from this is when you look at our web site and I right click and say

View Page Source, you can see that all the client gets to see, all my browser gets to see, when I try to

go to this web site

is just a plain and simple HTML web site.

I am not privy to any of that Javascript code that was executed to calculate the numbers.

All of that is hidden and taken away from the client side because we're doing it on our server.

And this is all because we built a backend that is doing the code execution instead of having all of

that Javascript run on the front end, which is on the client browser. And that is the most important thing

to take away.

We now have a web application because our code is running on the backend as opposed to just simply having

static files being rendered and loaded up, and having our Javascript run on the client side, or the front

end. Now in the next lesson,

I've got a challenge for you to try and solidify all of this knowledge that we learned in these past

few lessons.

So head over there and try and give it a go.

Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.