CMSC335: Exam 3
Session
time period in which a person views several web pages in a browser http is stateless -> every request is independent yet we want to track information throughout the session such as username, color preferences, data selection express-session module in node request.session.variableName stores variables request.session.save saves session variables request.session.destroy destroys sessions sessions rely on cookies
Router
to manage complexity of many routes in your app you can define files that take care of some of them router object that handles get/post/etc -> express.Router() const express = require('express'); const router = express.Router(); router.get("/", (request, response) => { response.send("/ in building.js") }); router.get("/iribe", (request, response) => { response.send("/iribe in building.js") });
fetch in node.js
u can use with no modules node-fetch
Dynamic Generation of HTML
view/templating engines - allow you to generate dynamic html EJS -> Embedded Java Script -> templating engine that compiles/generates HTML for you superset of html interpolate variables in template file with <%=variable name%> ejs inclusion <%file name%>
Logger Example
we can log requests using a third-party logger writeHead is used with text/html
Event Loop Process
when a new iteration of the event loop begins, a macrotask is selected from queue added after the iteration begins will not run until the next iteration each time a macrotask exits and the call stack is empty, each microtask in the microtask queue will be executed until the queue is empty, new tasks can be enqueue by microtasks before new macrotask and end of eventloop iteration
Debugging Chrome - Debugger Statement
- Add debugger to your code - Run the script - Right-click and select Inspect, and then Sources - Run the script - Execution will stop at the debugger statement
Time Events
- setTimeout() - executes callback after delay time (milliseconds) - setInterval() - callback is executed at periodic intervals- clearInterval() - clears timer
Extensions
.mjs is extensions of ES6 modules for use in node application .js files use the default module system -> commonJS if not specified in the package.json
Errors
Error Types URI Error Type Error Eval Error Range Error Syntax Error Reference Error you can use to throw an error define your own errrors
XMLHttpRequest
JS Object that will issue HTTP request no page load is generated as a result of request can only issue requests to urls within the same domain
Event Loop
JavaScript is single threaded has a call stack that supports the execution of code line by line supported by Web APIs each have their own macrotask microtask -> two queues where Web APIs place tasks event loop schedules and manages tasks -> event loops chose which one gets executed next
Traditional Server/Client Interaction
Nothing happens till we submit data We must wait until the server request is processed -> can't do anything with the page page must be completely loaded even most of the content is identical to previous page can we do better
REST
Representational State Transfer an architectural style not a protocol -> designed to operate with resource oriented services -> locate/manipulate allows diff data formats such as html and JSON fast and language/platform independent URL reps resources -> document, person, location each one has a unique URI -> identifier -> each resource dynamically generated not just document ops with HTTP methods
Middleware
a function in node a single function processes a request -> multiple functions do with middleware a request doesn't need to be processed by every middleware function it can be processed by whichever one responds a response -> server will hang if none do middleware can modify response and request app = express() app is a function that goes through the set of functions that are a part of the middleware stack app.use allows us to add functions that are part of the middleware stack
Cookies
a small piece of information sent by server and stored either in the browsers memory or as a small file on the hard drive acceptance of cookie depends on client browser sends cookie back with every request to server name/value pair no expiration date -> gone when browser closed expiration date -> gone on date node has cookie parser module response.cookie sets cookie response.cookies accesses cookies
Pyramid of Doom
aka Callback Hell when another async function is called in the callback of an async function in the callback of an async function
Express
an abstraction layer of node http-server provides: extensions -> request and response objects middleware -> executes in the middle after the incoming request and before the output -> can make changes to request and response -> the use function registers middleware routing -> associates url with an http method and some functionality views -> dynamic generation of html
Ajax
async JS and XML generates HTTP adds a layer between browser and webserver -> handling server requests and processing the results requests not synchronized with user actions
NodeJS
async event driven JavaScript runtime developed for scalable network applications can be used to develop full network applications relies on javascript V8 engine -> C++ & Just in Time good for performance
Retrieving Values Associated with POST
body-parser module allows how to retrieve parameters submitted during post request.body.argument_name
setTimeout
called with a value of 0; code not executed immediately; will place the callback in the macrotask queue
Async Refresher
can't use return can't inform about errors to return values or errors uses a callback function returns result or error function asyncFunc(callback) callback-function(error, result) error - error object or null if no error occured result - the result of the async computation
Polyfill
code providing modern functionality of older browsers
CommonJS Modules
define functions, classes, and constants in a .js file, .cjs file module.exports = {} to export entities use require in the file you would like to use the module in
Serving Static Files
express.static -> allows us to serve files path - built in module we use to generate cross platform path aka windows -> linux or linux -> windows
Asynchronous Programming
fs - file system Node supports async and sync versions of most file system functions sync -> code that performs one task after another, waiting for one to complete before starting another async -> we don't wait for code to finish, callback will take care of processing once an event has been triggering
ES6 Modules
functions, classes, constants in a .js, .mjs file exports = {} to export entities use import to use the module
HTTP Verbs and Methods
get -> gets a resource -> most common -> repeated execution does not cause server to change post -> generates a change of server state -> repeated executing changes the server put -> updates or changes the entire resource -> doesn't change the server state with repetition delete -> to remove a resource -> doesn't change the server state with repetition patch -> used to update specific fields express handles/curl executes
Node Project
has a file called package.json providing info such as project name, author, version, and dependencies
Axios
http client for browser and nodejs make XMLHttpRequests from browser make http requests from nodejs
Modules in Browser
if module is used in browser set script with type="module" attribute
Routing
mapping URI and HTTP verb to a request handler express -> specify with reg expression or string
Route Parameters
named URL segments used to capture the values specified at their position in the url -> values available in the request.params object » Route path: /users/:userId/books/:bookId » Request URL: http://localhost:3000/users/34/books/8989 » request.params: { "userId": "34", "bookId": "8989" }
XMLHttpRequest Functions
open - inits objects open(HTTP method, target URL, requestMode) requestMode - true for async, false for sync send - sends request
States of Promises
pending - async task finished fulfilled/resolved - async task done rejected - async task failed
Promises
prevent pyramid of doom placeholder for result of async function encapsulates two functions resolve() -> returns result reject() -> notifies errors async function receives promise with code instead of callback function callback provided with then()
then()
promise method with two callbacks as arguments first handles result second handles errors reverse of just using callback returns promises which allows successive calls asyncFuncA() .then(result => { // code for asyncFuncB }) .then(result => { // code for asyncFuncC })
process global object
provides information about the Node environment and the runtime environment standard input/output occurs through process process.stdin process.stdout process.stderr
XMLHttpRequest Properties
readyState: 0 - uninitialized 1 - loading, placing data in object 2 - loaded, loading complete 3 - interactive, object interaction possible 4 - completed onreadystatechange: event handler called when readyState property changes responseText: results in text form responseXML status: HTTP status statusText: HTTP reason phrase
Additional Request/Response Functionality
request.ip -> ip address response.get -> to obtain http headers request.status -> status code response.redirect -> redirects to particular site response.sendFile -> to send a file response.json -> sending JSON response
Retrieving URL Parameter
request.query.<argument_name> to retrieve url parameters included after ? in get
Debugging Chrome
right click -> inspect select sources click on source line number to set a breakpoint reload script to run expand panes to see local and global variables look at the top part of the right pane and step click on call stack to adjust the stacks
global global object
similar to the browser global object -> window provide access to all globally available Node objects and functions
Modules
split features into multiple files (modules) contains class or library of functions just a file -> one script one module two JS module systems CommonJS -> node.js use require ECMA Script Harmony -> use import
