Lesson 40
Email newsletter subscription backend with Express.js - Software School (2024-05-13)
Source Code: https://github.com/nbktechworld/introduction-to-css/tree/backend-for-newsletter-subscription/newsletter-subscription
Video Transcript
Okay, so in this session, I will build a back-end with the Node.js programming language, that
is JavaScript server side, and we will leverage the library from NPM called Express.
To start off, we will build this on top of an already existing front-end.
It's a basic HTML page that we built before in this repository here.
If you click the directory newsletters.subscription, this is the app.
It's basically a widget that allows you to type an email address and click to sign up
for some sort of newsletter, except this is what's just the front-end.
We don't have a back-end, that is, nothing happens when I click sign up.
So this lecture is about that other part behind the scenes.
What happens when you click sign up?
That's what we're going to build today.
Like I said, we will leverage Node.js, so make sure you have that installed.
And that also comes with NPM, that's the Node package manager that allows us to install
third-party packages.
And this is the website for the library we will use.
Okay, so essentially, what you can do is if you haven't done this exercise yet, just go
to this repository, you can click code, and you can either clone with Git, if you have
some knowledge of Git, or you can download the zip.
I'm going to do Git because I already have it, and I'm going to choose SSH, and I click
copy there.
Now what we're going to do is I'm going to my terminal, make sure you open a terminal,
and then go to a desired location, and you can do the command git space clone space,
that URL, and if you press enter, it should clone it if you wish to do so via Git, otherwise
you could have just downloaded the zip through GitHub itself.
In any case, I already have it, so I press enter is going to give me an error, but you
can do a listing, and I have it here, and you can CD to it, introduction to CSS.
Make sure you enter the master branch, you do Git branch, and then if I do a listing,
by the way, if you're using, I'm using Windows command prompt, if you're using Mac or Linux,
the terminal command to list files, it's LS, okay, LS.
If you use PowerShell Windows, that also works to do LS, it's just an alias to another command
that PowerShell uses.
In any case, I'm interested in newsletter subscription, that's the one I want to go CD to, and if you
do a listing, you have a file called index.html.
Anyway, I'm going to open my Visual Studio code, that's the editor that I use, if you
have another one, that's fine as well.
I can say code space dot, which means open the current directory, Visual Studio code.
Now one moment while I share, okay, so let me just resize my window here, share.
So this is that directory in the repository, and I'm interested in index.html as a refresher.
This is basically a very simple website, an HTML document, and more interested in this,
we have a label email, and they have an input email that you can type to sign up for the
mailing list.
And here's the screenshot of what it looks like, and we're going to open it very soon,
just a moment.
In any case, I want to also demonstrate, you can also open this.
So we have to open index.html to be able to see the application, or if you know how to
open a web server, you can do that as well, but let's keep it simple.
I'll just open index.html in any browser of your choice.
For example, I can go to the file explorer or finder or whatever, and I can right click
index.html open with my browser of choice, in this case Firefox developer edition.
And that should open the website like this.
If you for some reason don't know how to get to the location of your own project, if you're
within your Visual Studio Code or any other text editor in the sidebar for the explorer,
you can right click reveal and file explorer.
There should be an option like that, and that should open that file explorer window.
Another option to do this is extensions that can live preview the HTML within the Visual
Studio Code or any other editor.
So if you know how to do that, feel free to do that as well.
So with that said, I'm going to take a moment to assess if everybody is on track.
So I'll let you chat.
Let me know if you have any trouble so far.
Everything okay?
So I'll keep going.
All right.
So what we want to do here, let's
open the terminal here.
So I need to install Express.
So to do that, I need NPM, the node package manager.
But we have to initialize this project here.
So going to the terminal, make sure you are in the director for newsletter-subscription.
And you want to call NPM space init.
What this does is create the file package.json.
You can do it manually and create the file, but this is very useful to generate that file.
It will ask you a few questions like what's the name of the package, the version, so on.
I'll just use default.
I don't really care right now.
It can always change later.
Enter, enter, enter, enter, enter, enter, enter, enter, enter, enter.
Is this okay?
I'm going to say yes.
Enter.
And that's it.
That generates the file package.json.
If you go back to the text editor, you can see the file is now created here, package.json.
Now going back to the terminal, I'm going to NPM space install space express.
And this is going to pull this third-party code for the Express library.
Okay, going back to Visual Studio Code.
I should now have in my package.json an entry here called dependencies.
And you see Express is now listed here.
And this is the version that I was installed, 4.19.2.
Okay, you might have noticed that it also generated this file package.lock.json.
This package.lock file is very common.
You don't have to worry about it.
You can also commit that to version control if you'd like.
You might have noticed that node underscore module's director was created.
And this is where all the third-party code that's installed by NPM goes.
If you expend that, you're going to see that Express is here.
You see this Express?
That's the one we just installed.
Now you notice there's a lot of other stuff.
And that's because Express has other dependencies on other packages.
So if you look at the package.json of Express, there's a hell lot of dependencies here.
So that's why you also see a lot of other stuff under node modules.
In any case, that's how you find out that's been installed.
We can go back.
Let me close this.
And let's create a server file.
Here I'm going to right-click, new file under the root.
I'm going to call this server.js.
OK.
Now this is where we write the JavaScript or Node.js code for the server side.
So first of all, we need Express library.
So we can require it like this.
So you call require for parentheses and then quotes, either single or double.
It doesn't matter in this case.
And Express, which is the name of the library.
This is the same name you see in package.json.
So what we do here is we place that in a variable, const, Express, like that.
Now let me disable something here, because it's going to get in the way of giving one moment.
All right, I'm just going to restart this.
One second, OK.
All right.
Anyway, require Express.
And then you're going to put that in a variable.
And then you just call it like a function.
And then you can place that in another variable.
We usually call it app.app.
Then finally, we're going to say app.listen.
This is the function we call so that the app boots up.
Now if you do it like this, and I can open here a terminal within my Visual Studio Code,
pressing Ctrl, back tick, you can choose a terminal here.
If you use Visual Studio Code, I'm going to choose Command Prompt.
And this is just for convenience.
You can also do it separately in a different window other than your own editor.
And you can type here the command node, space, the name of the file, this case server.js.
If you press Enter, you're not going to see anything, but it's actually running the server.
OK, but one thing I didn't mention is you need to say, OK, where do you want to run it?
In what port?
So let's kill the server control C. And let's explicitly say I'm going to run a port 3000 here.
That means if I want to access it, I'm going to go to localhost colon 3000.
Or if you don't like using localhost is 127.0.0.1.
In any case, going back to the terminal, I'm going to do node server.js again.
You don't see any prompt yet.
And that's intentional because I'm going to let you know later how we can add a feedback there.
But it's running the server.
Anyway, going back to my browser, I'm going to open a new tab and say localhost colon 3000.
And I'm going to see this message cannot get slash.
If I see cannot get slash, it means it's working properly.
There is a server.
OK.
Now, how is everybody doing so far?
I'll let you chat if you want.
So far, so good.
No trouble.
OK.
Let's go on then.
OK.
If that's said, going back to Visual Studio Code, you can see there's no feedback about
the server running, but it's actually running.
So we want to add here as the second argument to this function, listen, you want to add
a comma and then the second argument is callback function.
Now, you can type it as an arrow function like this, or you can type it as a function
like this.
It doesn't matter.
If it's an arrow function, you just write the parentheses and then equal sign greater
and then the body of the function within the curly braces.
So here I'm going to say print a message to the console.
So I'm going to say console dot log.
And I'm going to say server is running on HTTP colon slash local host colon 3000 so that
I know something is happening.
So whenever I change my code here, I have to go to where my terminal is running the
server and actually restart it.
Now, to do that, you first do what's called killing the server or shutting it down.
In this case, you can do the control C control C sends what's called the interrupt signal.
So when we do that, it stops the program.
Now we can call it again.
If you don't want to type it again, usually I press the up arrow in my keyboard so that
it sees the previous command and I press enter.
Now I can see there's a feedback message saying that server is running on HTTP colon slash
slash local host colon 3000.
So this is also nice because I can hold the control key my keyboard and click this URL
and it follows it and opens the mind browser.
So I don't have to copy and paste.
So that's just a nice thing.
So we know that the server is running and it's going to work the same way.
If you go to the browser, local host 3000 refresh, same thing.
Okay, well, let's talk about going back to this.
This is the app on the front end, right?
The newsletter widget.
So I'm going to type an email and I want to click sign up.
I want something to happen this form to be submitted.
Now what's going to happen is we make what's called an HTTP request to a backend server.
In this case, we have express listening.
And then we need an endpoint or a route.
Like I need to ask express, hey, I want to sign up for the mailing list.
So I need to tell it, okay, I understand HTTP.
So HTTP, I have a method.
It can be usually get or post.
And then I need to know what's the path to the resource you're trying to reach.
In this case, we can just make it simple.
Let's call it slash subscribe.
How about that?
And then that's it.
Express will do everything for us.
We're going to write the code in a bit.
So any case, let's go here to Visual Studio Code before you listen.
And after you create the app variable, we can establish endpoints here by saying app dot whatever method for HTTP there is.
In this case, usually get or post.
When you go in the browser and you type in the address bar and you press enter,
that's actually making an HTTP request.
And it's the method is get, okay, to that path that you typed.
So in this case, because of the form submission, we typically use post.
Okay.
So let's do post.
Now we call it as a function.
And then there's two arguments versus the path.
So in this case, I want to say slash subscribe.
So when I say slash for subscribe here, I mean, it's going to go to HTTP localhost 3000 and I must say it like this.
And the route has to be post.
Okay.
So I put a slash last year.
So it's a comment just for reference.
But this is not really code that's going to be executed at all.
Okay, so this is going to listen.
And if anybody tries to make an HTTP request post slash subscribe this one, it's going to do something.
Now that's something we have to write as the second argument.
And it's a function.
You can either type like function like this, or you can use the arrow function like I did in line 10.
So there's two arguments or parameters to this function versus the request and then the response objects.
We usually say req and res for short, but they just you can write name it anything you want, but they always mean the request first, and then the response object.
Okay, just for the sake of having an example, I'm going to send a response right away.
So the way we send something we reply is by calling the rest object dot send function and you call it like this.
Now you can send it empty response.
That's fine.
You don't have to provide any argument, but typically want to send something back.
So one thing you could send you can send a text you can send HTML page.
You can send Jason, you know, up to you.
For example, let's just send some plain text.
You were subscribed.
Then let's save that now whenever I change my code, I must take care to go to my terminal where the server is running control C to kill it and then do the same command again.
Every start.
Now let's try this out.
Going back here and the browser.
Now we don't have code to make a request yet.
Let's see how this is hooked up by inspect of tools.
So we don't even have a form here.
So we have to work do a little bit to work on the front end place all this input in a form tag and then add the method and the action.
Now the method is posed and the action is going to be this you are out to the server slash subscribe.
Let's go to the front end code and visual studio code index dot HTML.
Let me we can always hide the if you're using built in terminal we can hide it click in the x and I can bring it back control back tick.
So the server still running there in the background.
Anyway, I want to locate the input here and we got a label and it's inside a div of class form group.
Okay, that's fine.
So I'm just going to close that in a form.
Okay, I can use alt up to move lines on visual studio code alt up key.
And, okay, to the form we need to add the attribute okay what's the method here is it get is it post well we'll use post.
So I type out caps usually, but I think I don't think it matters if it's all caps.
And what's the action okay where you want to submit this to well HTTP colon slash slash local host colon 3000 slash subscribe.
Okay.
And we also need a submit button to this form.
So maybe I want to move this button here within the form.
Okay, I move the button under the form before it's closing tag and make sure the type is submit.
If you use a button instead of input button type button we want to sure it's submit there.
So when I click submit button, it's automatically going to do whatever this form is hook up to do.
So save that.
So I'm going to go back to the browser and I'm going to refresh because I made a change to the code to the front end so I want to get the new version.
And here my dev tools can I can confirm that the form is indeed here with the correct method and action.
And by the way, if you don't know how to open dev tools at F 12 key, or it can right click anywhere, click inspect.
Now my browser right now is Firefox.
And if you're using Chrome is the same thing any Chromium based browser.
Same thing you might see some different labels.
For example, you might see elements tab instead of the inspector best the same.
Anyway, I'm just going to try to see actually it's always good to open the dev tools and click the network tab to monitor the request.
So I'm going to monitor it to make sure I'm doing the right request.
If it's going there.
Mail at example.com going to click sign up make sure the filter set to all here.
Otherwise it might be filtered by other types of requests.
Okay, so I can see the message you were subscribed.
And you can see it went to local host slash subscribe right.
So that was submitted.
Now if I monitor my dev tools you might have noticed.
There's some requests there are row by row I click the second row and then finally, I can see.
Let me see the response.
Try to see what's why it is not saying my stuff.
Maybe because, okay, when I submitted that form it opened a new page.
And I lost all the things that I sent.
Typically today, when we send a request to the back end, we usually don't reload the page, we send what's called a XML HTTP request.
But since I'm doing the traditional way here, it loaded a whole new page.
I lost the things that are submitted.
That's actually there.
Okay.
So how's everybody doing so far?
I'll let you chat if you want to send a message in the chat.
Got stuck somewhere I need help.
We're so far so good.
Okay, I'm going to continue then.
Okay, let's go here back to Visual Studio Code.
Now, our form submission is hitting the back end correctly, because you saw the response, right?
Going back to server.js, you saw exactly what I typed here in line seven in server.js.
And that was just plain text.
Now, we want to be able to read what the user sent us, right?
They sent the email.
Now, let me check the front end or click index.html.
Now, because I'm using an input here, one thing I have to do is make sure I label this with a name.
Not the sense of label attribute I'm talking about.
Okay, the back end is going to receive something.
That's the email.
But usually forms have many fields, right?
How do I know which is which?
So I need to add a name attribute here to say, what is this information?
So give it a descriptive name.
I'm just going to say email, because that's what it's meant to be.
So that way the back end will see a name property with it.
It's going to say email, and then the value that the user typed.
Now, going back to server.js here.
So there are different ways to process the information that's passed.
Okay, so the traditional way is URL encoded.
The modern way is with JSON.
Let's do the traditional way.
So in the HTTP request, when you make a post request, you're going to include that information in the body of the of the request.
So the back end here has to process that and extract that information from the request.
Now, to do that, we're going to use what's called a middleware.
So an express middleware is something that stands between the client and the final response.
When I say final response, I mean this function here that we call to send back the reply.
So that middleware is going to be a response.
Okay, if it finds out that you're receiving form data, it's going to extract that and put that in a variable.
So here in my function, we're going to be able to access that by just saying rack dot body.
Okay, that's the request object is going to create this property body with whatever was coming in from the form.
And to just to confirm that's working, I'm going to do a console dot log of the rack dot body like this.
And usually I want to identify this log with message, some string saying rack body or request body, whatever.
So that when we look at the console, we're going to identify this string request body, followed by the value here.
If it was just request rack the body, I didn't know what they was, you know, if there's so many logs to the console.
In any case, the middleware here, the way you apply a middleware to express app is just saying app dot use.
That's the function and you call it.
Now you need to give it the middleware.
Now it's you can use the one from built in from express and there are several ones if you want to JSON is JSO win.
And the one we're going to do is URL encoded.
And then you call it like that, you can give some options in an object.
But let's try just a default to see if it works just by default.
So make sure to call it by the way there's a parentheses calling that so it returns a function and that functions in and actually pass to use.
Let's go to the browser.
Oh, actually, I have to restart the server right because I changed the code control back tick.
I will kill my server and restart.
Oh, it's saying deprecated on the fighting center provide extended option.
Oh, looks like this middleware.
I should provide an extended option.
Let's look at the docs.
See, they usually put these messages deprecated to let us know, hey, something has changed.
So make sure you follow the new rule or whatever.
So let's take a moment to look at that.
First, I'm going to go to the browser and I'm going to the express website, express.js.com.
Now I'm going to look for the URL encoded here in the search.
And by the way, I'm using 4.0, right?
Make sure you choose the right version of the software.
Let's click the 4.0.
And let's find out what's that deal about extended.
So it looks like there's a property that we can pass call extended.
That's a Boolean value.
That means it's true or false.
Okay, so it looks like I just got to make it true.
This option allows to choose between parsing the URL encoded data of the query string or QS library when true, blah, blah, blah.
Okay, you can read more in this page.
I'm going to paste in the zoom chat if you're interested in doing that later.
Going back to Visual Studio Code, I think I can just say extended true here and to get rid of that message.
Just put an object.
That's the object of options.
A property extended, make it true.
Save it.
I'm going to restart my server to see if the message goes away.
Yeah, I didn't see the message fabricated.
Now we're good.
Going back to the browser, I'm going to localhost 3000 and let's click back and I'm going to submit again.
Okay, let's have a look at the console log.
So we'll have a look here.
So I see request body in the log, but I see nothing.
Okay.
So what's going on?
I'm going to try JSON here.
You don't have to do it.
I just want to see what's going on here.
I'm going to add JSON here.
Kill the server and try it again.
Going back.
Oh, maybe it's, let me see if I have the name.
Oh, I didn't see anything because I was using the old version of the index.html.
I just saw in the DevTools, I don't have a name for the input.
Right.
That's why.
Let me refresh and paste it here.
Now I can have a name here.
Let me try again.
Oh, now I see it.
Back in the console.
That was the reason I was using the old version of index.html, which didn't yet have the attribute name.
So that's why I saw an empty string, sorry, an empty object for the request body.
And that's why it's important to always have a name so that it appears here inside this object.
You see the rack.body.
Otherwise, I won't see it, but you can see that's what I typed.
And then it's under the key email, which is the same value for the attribute name of the input.
Anyway, I'm going to delete this JSON thing.
That's why it's always important when you make a change your code to refresh or restart whatever.
And I haven't told you that there are ways we can automatically do that, automate, hot reload or other things, but that's what we usually do.
But for the sake of us being, I assume being beginners, we want to get into the habit of repeating this so we understand what's going on.
We have to kill the server restart or we have to refresh the HTML page so it gets the new version.
So that way, unless you do it so much, you remember, oh, that's why now I'm confident.
I don't need this anymore. I'm going to use the automated one.
So my life is more convenient in any case.
So now we can access rack.body.email here, and that will let us know what the user just submitted.
Now, what I'm going to do here, what we typically do is we take this information, we insert it into a database.
So we have a database running, a database server, somewhere else, right, different application.
And that database has tables, and each table can hold different kinds of information.
Table has many columns. One of the columns would be for the email address, and that's where we would store it.
But for the sake of us being beginner class here, we're just going to store this in a file that's going to simulate a database.
It's just a database, but in a plain text file using the JSON format.
Okay, before I go that way, is anybody, okay, anybody need help on anything?
Got stuck. Let me know the chat is enabled.
All good? All right, I'm going to go on then.
Okay, let's create a file here. I'll call it emails. Actually, let me see, emails there.
Or maybe it's better call a subscription to be more general. How about that? Subscriptions.js all in.
If it were a real database, I'd probably have a subscription stable. That's why I'm calling it subscriptions.
So the name of the file, they actually match exactly the database table name.
And this is going to be very simple. It's just going to be an array of objects.
And each object is going to have the actual email, for example.
We're doing JSON here. So JSON format, we need quotes here.
Someone at mail.com, for example. Now, usually databases would have an ID.
So if you want to add an ID, one, that's fine. But for the sake of us being beginner, just just have the email.
The ID is something that uniquely identifies every row.
But thinking about it, email could be the ID as well, because it's supposed to be unique, right?
There's no two people with the same email. So anyway, I cannot have a dangling comma there because of JSON.
Okay, so this is the format we're going to use. So if you have multiple people signing up, all we're going to do is add to this list.
For example, if another person signs up, it gets added like this.
If another person signs up, basically is going to add a comma and another.
Like that, okay? So that's how it's going to be stored.
So I'm going to save this for the sake of having something.
Now going back to server.js.
So when you choose to subscribe, submit the form, it calls this function.
And then, okay, we got access to the email via rack.body.email.
Now I've got to take that inject into the file somehow. Now to do that, first you've got to do the following.
You've got to read subscriptions.json file.
Now, very convenient in Node that it can just do require subscriptions.json.
Make sure I even put a dot slash to indicate in the current directory.
So this will automatically read the file and then parse it in JSON format.
You could have done it manually if you use FS read file sync and then a JSON dot parse.
Anyway, this is very convenient. It can just put in a variable and I get access to all the subscriptions.
So what we're going to do is this subscriptions is an array in JavaScript or Node.js.
So because it's an array, I can just say subscriptions.push to add a new element to the end.
And you pass in as the argument, the new element.
So that case is an object that has one property called email and the value will come from rack.body.email like this.
You can just put it there.
Basically, we're doing what I just did manually.
Remember, I kept adding copy and paste the same.
It's basically what I'm doing.
Going to the end, adding a new one with the property mail and the value, whatever was typed.
Okay, but this is just going to change it in memory.
It's not actually save the file.
So that's why we got to do got to overwrite this whole file with the new thing.
Right.
So to do that, we're going to call the FS file system module.
Go up here and require FS.
This is built in Node module.
It's for file system operations like writing to a file that is saved, right?
But then in a variable, I usually call it the same name as the module FS.
Now we can use that module.
There's many functions.
And one of them is write file sync.
That's the synchronous version of write file.
And we can pass.
Okay.
What do you want to write?
I need the file.
Right.
What's the path?
Well, the path is going to be dot slash subscriptions.
Got Jason, comma, the second arm.
Okay.
What's what do you want to write to the file?
Well, I want to write subscriptions, but that has to be a text.
Right.
So I want to take this array and convert to text in format Jason.
So to do that, I can call Jason dot stringify like this.
Maybe this is hard for you to see.
I can always cut this here and put it outside.
Let me put a variable const file content like that.
Now it's easier for you to see.
So basically I call the Jason module dot stringify function.
This will take the array converted to text in the Jason format.
So it's basically text plain text, right?
Sequence of characters.
And that store gets stored in the variable file content that I use for the second argument of write file sync.
Now the third argument that I usually always put is an array of options.
Sorry, array object of options.
Put an object there curly brace and encoding.
We want to make sure we use UTF eight.
Okay, either UTF eight or dash eight doesn't matter.
So that the file is written in the proper encoding.
Otherwise it might mess up.
And when it comes to reading it by somebody else, they won't understand it correctly.
So I was on an app that encoding, you know, I've had many problems in the real world with the encoding was not specified.
And it caused so many problems headache.
That's why I always suggest you put it there.
Anyway, this is going to write to the file with the new content.
Let's try it.
I save it, kill my server, restart.
And go back to the browser.
I'm going to click back, make sure I have the.
This is the right version, right?
I haven't changed the front end so I don't need to refresh.
Sign up.
Okay, I was subscribed.
Let's take a look at the file.
Subscriptions.json.
See what happened there.
I get email mail example.com there.
That's what I just typed right submitted before we had just this right I press control Z by the way.
This is before this is after right someone another hello and mail before someone another hello.
So it's working right adding to the end.
Now I might have noticed the formats ugly.
That's because of JSON stringify by default, there's no white space to make it better for us humans to see it.
So if you want it to have in this format like this, what you have to do is go to server.js and to the stringify function call.
You pass the arguments here.
So the second can be no, nothing particular, but the third is what matters.
The third, okay, how many spaces do you want in addition to.
Okay, so that means it's going to add indentation of two spaces.
You can increase if you want, by the way, display around, but I like two spaces for indentation.
Indentation is just the space to the left of the beginning of the line, right?
Every time you have an open curly brace or bracket, we always indent or add two spaces starting on the left.
Anyway, kill the server.
We start.
By the way, let me before I do that kill the server.
I'm going to revert the file to the previous form, okay, like this.
And actually, I'm going to make it ugly like before so that you know that's going to format it.
Okay, this is the ugly version.
And there's four things.
So restart the server.
By the way, I took care to restart the server after saving the file because it's reading the file when I call when I restart the server.
So if I had in the previous version of would read the file as it was before.
So make sure you save the file before you start the server.
Anyway, going back to the browser back and click sign up again.
Then I'm going to go back to visual studio code, check the file.
Now you see it's nicely formatted now.
And I added the new mail at example.com.
How's everybody doing?
You can chat if you want, send messages to the chat.
Any trouble so far?
And comment.
The body asks, can you go over what is the middle where might we need it?
Yes, let's go.
So let's go to server.js here.
Let's comment out the middle where line seven.
So middle where when I say slash slash in the beginning of the line, this becomes a comment.
A comment is just code that's ignored by the computer will not get executed.
Now let's save that until the server restart.
Then I'm going to go to the browser submit again.
My form.
And you see what happened there?
An error occurred.
I cannot read properties of undefined reading email.
Now what happened here was I tried to access rack dot body, but that is undefined.
I tried to access email on something that does not exist.
That's why I got the error.
Now the reason we have middle where is so that we can extract what was sent by the form.
Now if I don't have a middle where here, whatever I sent via the form, that's an HTTP request.
Let me make it something here so you can see the request.
I'm going to go to the phone and let me see if I can do event prevent default.
Not sure I can do it.
Yeah, anyway, let me just, I don't have a JavaScript file for that.
So I don't want to get there anyway, going back to server.
So whatever submitted to the form, it's in the request, but to access it, I have to extract it.
Now I can do it manually, but that might be burdensome.
So what I do is a delegate the extraction of the form data to a middle where right middle where something in between middle.
So the browser is the client makes the request.
Hey, I want to submit my email and then it reaches the server the server lessons.
Okay, you requested what method was it post was it slash subscribe.
If so, here's the instructions that I was told to do.
Right, this function where we called.
But in this case, it doesn't know wreck the body is that's why we need something in between before I call this function.
Right, I want to have something in the middle to say, hey, I detected the form beta, therefore I'm going to extract it, inject that into the wreck that body object.
So that when I by the time I reach function here, I can access whatever the user submitted.
Okay, one of the middlewares is expressed URL encoded a middleware is very simple is just a function.
Okay, request, just like the handler we have here.
Like this.
So the middleware intercepts the request and it's going to check okay, check the request to see if form data was submitted.
If that was the case, we set wrecked our body.
Okay.
So that means what is it going to do wrecked our body equals extracted data from each to be request.
And then once that is done, it calls the next when it calls next say hey, I'm done here go, you can continue in the pipeline.
Something like that.
Okay.
So when you call this express you are encoded like this, it's returning this kind of function is just a function definition.
And that function definition is given to express via the use function.
So express is going to take the function definition.
And whenever you have a request that function is going to be called in the middle in between.
Now somebody said now I wonder what it would look like if you didn't manually without the middleware now to do the manually.
You haven't done it so you have to go to the request body, and you have to find wherever the information is for the body, and you have to parse it.
And if it seems encoded in any way you have to decode it.
Now if you want to find out more about the wreck request object, you can always console log it, or put a breakpoint if you know how to use of the bugger.
Let's say request object here.
Oops, no, go on there.
Go to server restart the server.
I put back the URL encoded by the way.
Let's go to the browser submit again.
That can trigger the calling of the function.
And you can see here in my terminal, I console log the whole request.
And there's a lot of stuff here.
Okay, but somewhere here how to find out where the permission is.
Now because Express injected this with the middleware, but anyway, you have to figure out it's a lot of low level stuff.
And if you want to find out more, let's just we can talk if during the score if you want, go to the documentation for express.
And you're going to get in the right left hand side, look at the request object here, you see request.
And there's so many stuff here.
And you can find out what each of them means.
And if you want to find out how it extracts.
Now, another way I can tell you, okay, you want to find out how is the express library built right that middleware.
You can always go to the source code because it's open source.
So you go express.js get hub.
The code is on get hub.
You can go to the repository and find out where the source is.
And there's that live.
And you see middleware here, middleware.
And there's the code is going to be here somewhere.
Okay.
And see request, response, express, so on.
But I think it's called this is actually coming from body parts.
You see this line here.
So that's the actual code is based on this body parts of thing.
So if you look body dash parts to get hub.
And this is the source code, you can go live and have a look the types you see you are encoded here.
This is the code that's doing all the extraction.
So you can have a look at this code.
I'm going to paste it for you in the chat.
If you're more interested in reading about it.
This is more advanced stuff is not for beginners.
Okay, to understand all this stuff.
But if you're curious, that's where it is.
That's what it's doing.
In any case, I'll answer your question.
To the extent of this scope of this lecture.
All right, so.
Any more questions or anybody else.
Back visual studio.
I'm going to remove this console log.
I'll leave this console log this for reference.
Like that.
You might have noticed that I have repeated emails right.
And that's actually not good right so what you got to do here I live as an exercise for you.
What you're going to do is here before you push, check if the email does already exist.
If so, you could just not sure if so either send back an error or just assume success in silence or whatever.
User won't will think it's some scribe.
Don't like that.
So two choices right if user subscribes what's already subscribed you can just let him know okay you are subscribed even though we already were or another way you're going to say hey you're already subscribed.
Why are you trying to do it again.
Either way works.
Anyway, and to do that you can just do a simple hint.
Use dot find function by array prototype dot find.
That's a challenge for you.
And by the way, if you want to send a response early, you just got to send res dot send like this.
You are already subscribed.
But what's important here is putting a return.
If you don't have return either before or after doesn't matter.
You're going to send a response and then you're going to keep running the code and send another response which is wrong.
So make sure you have a return.
So that's why I always advise people okay always put a return when you call res.
So I'm going to put a return there.
In case you forget or somebody forgets they put some code here that might cause a problem.
So anyway, so for this one you're going to say if it already exists or something, you know.
I'll put a variable here.
I'll let you do it.
I want to do it for you.
You have to do it.
If you want to change the status to something that's not 200.
If you're familiar with HTTP, there's different codes.
Status code 200 is okay.
There's 404 not found and there are others.
If you want to do, for example, 400 or 422, you can just say res dot status.
For instance, there's a new chain with the send here.
For example, 422 like that.
That way you change the status code to 422 before you send.
Okay, so if I save it like that, let's say already exists true here.
Just for the sake of the example, I'm going to set it back to false and you should make exercise yourself to use the find.
Let me kill my server and restart.
And I try to subscribe again.
You are already subscribed.
It doesn't matter.
Here's 422.
You see that 422 unprocessable entity?
It's here.
That's what I changed with the dot status parentheses 422.
Okay, going back to the code, I will refer that back to false and leave it as an exercise for you to do.
And that's it for this lecture.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? ๐๐
Consider a donation to support our work: