Lecture Script

Summary

Node.js HTTP Server Handling

Express.js Framework Patterns

Pug Templating Engine

Modern JavaScript Review (ES6+)

Variable Declaration:

Arrow Functions:

Template Literals:

Destructuring:

Spread Operator:

Rest Parameters:

Default Parameters:

Array Methods:

Async/Await:

Other Features:

TypeScript Introduction

Why TypeScript:

TypeScript Basics:

Notes

Transcript

So it's a way to ask the server questions about getting data back. And then. I said, I'll say that the request method is post. So this would be if data is coming in via post. And this is using The request object. and it's showing how you can read data out of the request objects and the body has to be read throughThis is so nice.

We're basically saying, On a data event, I will request Read this chunk of data and it's going to put it in the body and it's going to keep getting those chunks of data The body represents the body of the request. It's going to keep getting those chunks of data until it's done getting data. So remember, a request is coming in. and packets request is a single request. So it's building that body up. As soon as it hears it's done, then it knows that all the data from the request is there.

We have this body. We put it into the property. This is all just for the Exercise of Taking what's coming in and sending it back to the user. It's parsing it. It's using the JSON parse to take that body and parse and turn it into an object. So basically this is saying, I sent you a post request. And the body of that post request is JSON data. When we get the data, we know we have to parse it and turn it into real data.

If it's not JSON, that means the content type was not set to application JSON. We're going to just assume that it's just text data. I was trying to get some problems with this multi-part formulator, so I'm going to get to it and talk about it. And then in that case, I've got this parsable machine which It's coming in from this query string package. So there'sWhat's up? This is an old demo, so it's still using The common JS require imports.

This is another package that's built into Node. So I'm called Bruce Frank. -Who's the man? Basically If you have a POST request coming in and it's not JSON, The body is likely going to be URL encoded data. So we'll just see what the data looks like in body parts. Amen. So again, we're still in the post. Request. So it says if the requestStep pattern. Says they want JSONPath? I have to go with the saying, application JSON Then we're going to set on the response object the status code 200 to say, okay, we're going to be able to respond successfully if there's some kind of fail.

We'd have to set the status code to something else. 404, you know, we couldn't find the data at that path, or-500 status code if it's some kind of internal server error. And then we're going to say, OK, we're going to set a header that says the content we're sending back to you is application-based on, because that's what you asked for. This header is set for fours, that's just so we can do cross domain stuff.

If you had this app running on your domain and your Only talking to it from your domain, you don't have to worry about other stuff, but when you're talking across domains, you do.

This is basically just saying hello to Eagle Aim.

This isn't really a secure way to do this. In a real production app, you probably Probably. You want to limit the domains that can connect to your backend by specific ways of doing it. Allowing them to say, okay, you can connect from this domain or you can connect from this domain. This is just basically saying, don't care. Um.

And then this response end, that's basically saying, OK, it's time to send the data and the response back to the user.

And whatever we put in the function call for n is the body of the response. So in the body of the response, we want to use JSON stringify to take our big data object we built, turn it into JSON text, send it back to the user, which the user is expecting to get JSON text back. If that except header application JSON is not set. We fall into this else block. Still set to 100 status call, but this time we're saying, OK, now we're going to send you-we're setting the header for the content type that we are sending back to you is text HTML.

Send back JSON data elseNow, because the git is slightly different, That is handled Up here. Where we're getting some of the data out of the URL search parameters, because remember a git request is going to pass any data as query parameters. There's no data in the body of a given request, so we don't have to do this stuff. Read the data out of the mind. And then that's the vaccination and this starts the server.

It's just posting a request to that local host address and it's sending a name and an email in as a standard form. This is like your most basic standard form. So this is going to send a post request. The POST request is going to have data in the body instead of URL params. And the body, by default, will be URL encoded data, because that's where form goes. So we come back over here. For you, sir.

through a native browser, they expose to the question. And then we're going to do the processing. So we're going to use JavaScript DOM manipulation and stuff to get the values out of the form fields. Put together a fetch request. We're going to send a fetch request here with the POST method. And then here's where the headers are getting set. We're saying, OK, we are going to send the application JSON data as part of this request.

And we want to accept application JSON data back. And that's what's going to trigger the server script to fall into those other blocks that handle differently? And then we're sending the body of our post request is going to be that JSON data, which is just the name and email. I'll get those properties. Stringified. So taking that JSON object, turning it into a JSON string, putting it in the body, and then Using our promises here.

And then the other example that was in the repo last week We didn't have to talk about Is There was this basic express road And this again was Just like what we did last week where We used Express Generator and then we used that NPX and MPM check updates to update all the dependencies and then We took Copilot to convert it all to manuscript modules instead of common JS. And that's where this was a starting point.

We remember in the basic express it was app.get.

You can directly say respond to a get request, respond to a post request, or you can use this use middleware.

So just like all these here are middle,Calls middleware. Basically what middleware is, is Every request that comes in is going to get processed through all this middleware.

And it even gets processed through all the used middleware.

And as it gets processed, it either gets passed on to the next middleware or the response gets sent back to the user. So when we get into these The way this is doing this is this is basically saying, OK, For any path request that starts with to-dos, and I'm just going to talk about to-dos, We're going to use our to-dos router object. So what is our to-dos router object? Well, it's just what's being imported from this routes.todoes.json.

And then on the router, you can use those same methods, get, post, Just like you do on the app. Top level. And then whatever routes you add here, are relative to whatever the router is.

So again, this router is So every route that's inside to-dos is actually slash to-dos something. So this is just slash to-dos. This is slash to-dos slash add. This is a poster press that's slash to do slash and.

Okay, we'll look at the delete numbers first. So We need to find a route in Express with a colon parameter.

As we talk about building apps, we're going to see that we should never do any operations through a git request that will Manipulate. Manipulate data.

A GET request just is a link being followed? So, let's say you have Delete ID It's just a get request and it actually deletes the ID and that's a publicly visible link. like Googlebot or anything spiders that link and follows it, it would actually run the code.

They won't submit forms, but they will follow it regularly. So if you don't want to... Manipulate data until you get it close. But you can see inside both of these actually, because they both use that parameter, On the request object, There is a params property and on that params property will be every placeholder that you have.

This line here, so we talked about response send and responseUh, JSON?

In that last demo, there's also a response.render.

It's going to render it, and wherever you pass the second parameter is, that's a data object that is a JavaScript object.

And that data comes into the template. When we look at this template, we should look for where the data is being used that uses a title and then also a to-do object.

Pug is Not as User friendly to someone who is new to it because it's very different than what an HTML based template engine does. But once you kind of get used to it, if you start working with it, struggle through it, it does become pretty easy. Basically, this is saying, extends layout, So it extends this template. And so it's using the title variable. We already saw that that's coming through. And then it says block content.

So in our delete to do, We have this blocked content. So that's what's getting fed into the layout template and it's putting this content in.

And Pug is all based on indentation.

A link that has an href here. And then it says if to do is that length, that's part of the variable that's coming in. To do's. Right? It sends the data it's sending to the to-dos template. It is the title and then also In the to-dos key, it's sending the data, which is an array of to-do objects. There's only one right now. So It says, okay, if it's greater than one, Make a div with this ID and then inside that make the order list with this class.

And then use each val in to-dos to loop over to-dos. And it's basically a for-of loop. And then create a witness item. We kind of just see how it's, I'm trying to remember what, it's been a while since I've done it, but like three dashes now.

But some of this is to control white space.

So again, this is just a quick refresh to prepare us for type script. So Real quick. Let and cut.

In Latin cons, the reason we use those is they're block scores. So... Uh... The word var, or the keyword var is functionally stoned.

What it protects is the binding of an object to a symbol. So when I say symbol, I mean like the name you assign a variable. It protects the binding. It won't let you put another object or another Something that's stored in memory. attached to that name, but it doesn't necessarily prevent you from manipulating or modifying the contents of that object. So what does that mean? So let's just real quick look at an example.

with a new object, a new piece of memory. Boy. If we say user.name,It's set to Right. And now we look at user. It lets us change the data that's inside. Don't let that trip you off the cards.

So CONS does protect bindings, but it does not protectThe actual thing. Best practice here is you should They used to say, "Let is the new var." And now let's cast this roulette. Should use constant? Now it's by default. Unless you know you're going to need to reassign that value, then use let. And then just avoid VAR unless you have a very specific reason for it.

Error functions. So this is our other syntax for writing functions.

The very common use for these is callbacks.

And then it's the same thing. You call it this function expression. Differences here, function declaration, these can be defined.

after they're used.

But if that's all the function's doing, You can also get rid of the block altogether. And Get rid of the returns, David. And if the function, the arrow function looks like that, basically it's, If it's like a one line thing, it has an implicit return and it's going to return whatever this value results to. So you could say, is equal to... Right. So... That there Arrow function, when it's run, is going to return true or false.

When I said like as a callback, This is a good example. So we have an array, could be stored in a variable, 1, 2, 3. We'll call it the array map function. So the array map function takes a function in it that's going to loop over every element of the array. This is Almost all the time at this point it will be defined as an arrow function. Right in front.

So anytime you need like a little inline function, that is evaluated for some kind of callback, arrow function should be your go-to. We could technically define a function outside there and pass it to it, but Unless it's something you're using a lot, Most of the time, I just see stuff, but I get a lot of stuff.

Regular function definition, so this kind. Creates a new context inside them for this keyword. I'm not going to go to this too much.

Whereas an arrow function always takes the value of this keyword from outside.

I don't have an example handy for that to show. Let's talk about template literals real quick, because this is going to be something we're also using a lot, just to make sure everyone This is a new way of creating strength using back jacks. And then it lets you do variable interpolation with the dollar sign brackets and also multi-line strings. Okay, so something that looks likeLike this.

Right? This is a normal string. This is a template literal using the back ticks. And as long as until the next back tick comes, you can go on multi-lines if you want with the string just for readability.

Sometimes called multi-line strips. is because it uses back ticks to start and end the string, You can more easily use single and double quotes inside the string. Because you don't have to worry about like, In this case, if we try to do that, We're gonna have a problem and then we're gonna have to come in here and escape the that simple quote because it thinks it's the end of the string.

So all destructuring is, is that it lets us Take... An object? We can do it with arrays too, but more often than not, we do it with objects. Take an object and pull just individual keys, properties or keys out of it.

So it's passing that data all around and just to structure out that one property. And it looks so good. Something like this. So if you have this object called user, It's got these properties. You can use destructuring to say, oh, I want to declare a new constant called email. And a new constant called roll. And I want... them to be restructured out of the user object. that uses those names. So they have to be the same.

Structural boundaries. I'm not going to use a bunch of these properties, but I'd probably best just keep it at the essential. Array destructuring. Looks the same except it's with Square brackets, and since arrays are numerically indexed things, It's just gonna pull them out by their own hands. So, this is going to be the first value, this is going to be the second value, and we can skip any value. Well, we can't skip any.

The State is a common place where this destruction is used a lot. Couple of weeks and we will be over there. Spread operator.

Courage, mutability, common frameworks, all this. Prevent some intended mutations. You see why that's the case here. And then spread is used to create new data instead of modifying existing data. So again, that's part of it. We're making copies.

So in this case here, we have this nums array, 1, 2, 3, 4. We create a new nums array. And by doing This spread operator on nums, what we have now is a new array that has 1, 2, 3, 4 as individual values in it, and they're actually new values, right?

And then we have a new framework which we don't want. We want to spread out that array into these individual values.

Same thing can go withObjects? So we have this object, user, name, and balance. This is kind of a place that you will see this sometimes. is This syntax here basically says take every property that's in this existing object and make it properties on this new object. So if Is When this is done, updatedUser is going to be an object with name:alex,activeTrue.

Rest parameter isRest parameters is kind of like A similar thing, syntax is the same, so I'll just be mindful of it. We usually use this when we're compiling our function to allow for An unlimited number of parameters.

So I kind of think of it as like, even the rest of the frame They use the same syntax, which is three periods, but they're very different.

It looks something like this. You're declaring a function that's called sum that can take any number of parameters? So you do dot, dot, dot numbers, and now inside of that function, All of the parameters that are passed in will be given to you as an array.

Default parameters, functions can have default parameters. This is helpful. So if a parameter is notPast, or an argument is not past when the function isIs called. It will take out a default valve.

When you give it the parameter, you just give it a default value.

Look these up in MDN and be very familiar with how they work. Once you'll want to know how to useGo through, reduce, find. Probably the cat, too.

These are all, the reason they're very useful is every one of these is processed on an array and it gives you a new array as a result.

It doesn't modify the existing array. So it leads to a functional style of programming where you're not--State your Processing it and giving yourself a new result. Um...

which means it keeps it in the noose set. And if you return false, and it takes it out. And it's just a quick way to give you a new array containing all the objects that Match your filter function Again, with React, This is going to be stuff that you'll see used by the band because we never want to mutate the props. So we'll want to take that data in and use these array functions to process it. You can do something with it.

Array methods, because they return new arrays, you can keep changing them.

So like in that example we had, filtering them and then mapping.

Okay, async awake, I'm gonna be using this in a lot of examples as we go too. So you saw the one earlier, the, what was that? The Ajax version of the post-pack I had to fetch that used a lot of promise on wrapping. So, a single wing is the new syntax for dealing with promises. The way that It works. It's basically the await, you can think of the await keyword as like telling JavaScript toWait for it.

And then when it comes back, Unwrap the promise for you.

So what you normally do with that "got then" statement A weight does for you. Let's see what I can go with.

So the only place you can use the await keyword is inside an async function. So you have to define your function as asynchronous.

And then what this basically means is When this code runs, It's gonna stop doing anything until this fetch comes back. When this fetch comes back, It's going to automatically do what the Venn would do and You know when you call that on a promise, you pass it like a function that's going to process that piece of data.

Say don't go any further in our code until you get that response I just said that await can only be used inside async functions. You see here I'm not using it inside an async function.

The only other place it can be used is in modern JavaScript engines. It can be used at the top level of a file.

The only thing that This example doesn't show that what you really should do is something like this. So whenever you use Asic Await, you should Use tri-catch blocks.

Because That's the way it does error handling. Whereas in Promises, like that one that we had, This promise where it's Then there's a catch block on the end of the promises that hand is theirs when you use true promises. Because you don't have that with asyncoid. You should use trackers.

We're talking about the optional chaining.

Before You chain additional things and then This would result to undefined. It won't throw an error when you try to Access a property, I will notify the object.

But by using this optional chaining you're saying If Avatar doesn't exist, just don't.

Same line, knowledge, coalescing, coalescing. This is a way to provide fallback values. So there is some syntax where you use the OR statement. to be able to do fallbacks, but sometimes you want to use This noise operator instead. Because Or syntax. So... These look like this, right? In this case, input is an empty string If we say input for default,We all, this, I think that will evaluate you. That is the runway way to Basically that's one way to set a default.

Because this will only Evaluate to the second part of the expression. If the first part is null or undefined, So a small difference. This one is if input is anything false, use the second value. This is if it's only dollar on the front.

That's where you could fall into a problem with this one, because it's going to think this is false. But it might really be just an empty string. Whereas when you use the Knowledge Coliseum, it will only use the defaults if it's undefined.

Type JavaScript. is dynamically timed. So that just means any variable can hold any data type at any time.

but your code is expecting it to be a number to be able to calculate a value or something.

But you set it to a string because the data came into a form or something like that. That's going to happen and you're not going to find out about that error until you go to break with them. Whereas with TypeScript, Because with TypeScript you are statically typing everything.

And the TypeScript interpreter is checking your code, at least if you have, like, Visual Studio Code or any editor that's got the TypeScript language server running in it. Otherwise you can run the TypeScript compiler to check it too. But I typically do it through VS Code where it's constantly checking.

And it'll be like, whoa, this can only take a number. Why are you for the string? You'll catch errors. before they become a problem. Um, no.

It also It kind of goes to what I said earlier where we take all the modernness of modern JavaScript and we can use the most cutting edge modern JavaScript we want because it's intended to go through a compiler.

Now, I say that with There being a little bit of a shift now with Deno and Bun both running TypeScript natively.

But for the most part, especially deploying anything to a web browser, you have to build into it the JavaScript. That's the first thing to look at tonight is what it looks like to bundle, or not to bundle, to build. Um...

We'll see that with an example tonight where it's going to turn things into bars. Just this. And again, it's just going to add safety and developer experience to more clarity of what you're writing and what you can do. It can be annoying at times. Especially with like today I was working on something that we didn't have any of the The interfaces, which we'll talk about in a little bit, were fine for any of the data types that I was working on.

So again, just a quick high level, I'll spend like a minute or so on each of these slides. TypeScript is just a super set of JavaScripts, so everything you know from JavaScript, Translates right to transfer. That script just adds additional stuff on top. Microsoft development, open source, free. They develop a couple of products. The most important is the TypeScript compiler itself. They have a TypeScript language server that can be added to various The time script compiler is used for basically two purposes.

One is it can be used to convert TypeScript source code to JavaScript source code, but it also will, as it's converting it, will Highlight errors. Yeah. If you just write in notepad, and then run it through the TypeScript compiler. That's how you're going to find your TypeScript errors. When you're using it in an editor that has the TypeScript language server built in, that's when the editor is going to constantly be checking your TypeScript source.


Node.js


Node.js 개념


Node.js의 역사


Node.js의 특징