week 5 Flashcards

1
Q

intro to HTML

A
  • Hypertext Markup Language
  • markup language for creating web pages and applications
  • contains elements and attributes, that web browsers parse in order to render the content of the webpage
  • structure and content of a webpage is defined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

HTML5

A
  • DOCTYPE declaration
  • character encoding (charset) declaration , converts bytes to characters
  • features to embed audio and video files on the web page and provides the support to run JavaScript in the background
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

common HTML tags

A
  • <div>: defines a "division of the page"
    </div>
  • <p>: defines a paragraph
    </p>
  • <span>: an inline tag for grouping text or elements</span>
  • <b>: bold text</b>
  • <i>: italicized text</i>
  • </i></b></span></p><h1><b><i>, <h2>, … </h2><h6>: these are headings, h1 is largest and h6 is smallest</i></b>
  • <br></br>: line break
  • : defines a table. defines a table row, </h6> defines a table cell, and is used for table headers
  • <img></img>
  • <ol>: an ordered list. <li> to list items.
    </li></ol>
  • <ul>: an unordered list. <li> to list items.
    </li></ul>
  • <a>: makes a hyperlink</a></li></ul></li></ol></i></b></h1></div>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

HTML5 non semantic elements

A
  • not related to the content on the web page

<div><span></span></div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

HTML5 semantic elements

A
  • used to define the content and on the webpage

: defines a thematic grouping of content
: represents a section of content that forms an independent part of a document or site such as Forum post, Blog post, Newspaper article, etc.
: specifies a header for a document or section
: define the footer for a document or section. contains information about the author of the document, copyright information, links to terms of use, contact information, etc.
: major navigation blocks that specify a set of navigation links
: identify content that is related to the primary content of the web page
: describes some flow content, optionally with a caption, that is self-contained and referenced as a single unit from the main flow of the document
: add the visual explanation / caption of the image
: used to add details that user can view or hide
: used to highlight or mark the text
: defines a obvious heading for a details element
: used to add a date/time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

HTML5 audio tag

A
  • element used to embed audio in a web page
  • element defines sound content and it has a controls attribute that adds audio controls, like play, pause, and volume. Any text within the and displayed on the browser only if the audio was not supported by the browser.
  • element defines the media resources for the audio files and it has attributes such as src and type. The src is used to specify the file format of the audio content and type specifies the media types that element supports.

file format ==== media type
MP3 ==== audio/mpeg
OGG ==== audio/ogg
WAV ==== audio/wav

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

HTML5 video tag

A
  • element used to embed a video on a web page, such as a movie clip or other video streams.
  • any text between the and tags will be displayed in browsers that do not support the element.

attribute; value; description

  • src; URL; Specifies the URL of the video file
  • controls; controls; Specifies the video controls such as a play/pause button, etc
  • height; pixels; Sets the height of the video player
  • width; pixels; Sets the width of the video player

format ==== MIME-type
MP4 ==== video/mp4
WebM ==== video/webm
Ogg ==== video/ogg

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

starting HTML documents

A
  • – : metadata. for character encoding
  • – : actual content of page to be shown on screen
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

elements (HTML)

A
  • provide the structure of the document
  • defined within HTML files using tags (ex. <div> </div>, <img></img>)
  • may be nested within other elements
  • tags must be properly nested to be valid
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

attributes (HTML)

A
  • key/value pairs that give metadata about the tag that are important for the browser to know
  • ex. <img></img>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

global attributes (HTML)

A

can be applied to any element on the page

  • class
  • id
  • hidden
  • lang
  • style
  • tabindex
  • title
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

HTML form

A
  • a section of a document that contains controls such as text fields, password fields, checkboxes, radio buttons, submit button, menus, etc.
  • using these elements the page can collect information from a user which is typically submitted to a web server.
  • tag used to create forms
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

attributes used in HTML forms

A

for use on tag and elements

  • action: indicates where the form data will be processed
  • target: used to specify whether the submitted result will open in the current window (is default), a new tab (set to “blank”) or on a new frame
  • name: should be provided for each input element
  • method: used to specify the HTTP method used to send data while submitting the form
  • —- GET: form values will be visible in the address bar of the browser
  • —- POST: form values will NOT be visible in the address bar of the browser
  • value: specifies an initial value for an input field. also serves as the attribute to use when providing a button label for submit and reset input elements.
  • placeholder: specifies a hint that describes the expected value of the input field (a sample value or a short description of the expected format). short hint is displayed in the input field before the user enters a value. works with the following input types: text, search, url, tel, email, and password.
  • required: indicates an input field that must be filled out before submitting the form. works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
  • min and max: specify the minimum and maximum values for an input field. work with the following input types: number, range, date, datetime-local, month, time and week.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

input elements in HTML forms

A

specify an addition type attribute to indicate which field to display

  • text field: one-line input field that allows the user to input a line of text. created by specifying the type attribute value as “text”.
  • password field: type of text field in which the text entered is masked using asterisk or dots. created by specifying the type attribute value as “password”. not encrypted.
  • radio buttons: let the user select exactly one value from a list of predefined options. created by specifying the type attribute value as “radio”.
  • checkboxes: let the user select one or more values from a pre-defined set of options. type attribute value for checkboxes input control is “checkbox”.
  • file select boxes: allow the user to select a local file on their computer and send it as an attachment to the webserver or write path and name of file. created by specifying a type attribute value as “file”.
  • text area: multi-line text input control which allows users to provide a paragraph or multiple lines of text. It is created by using the “textarea” element. DO NOT use the element. use attributes “rows” and “cols” to control size of text area.
  • select boxes (drop downs): allow users to select one or more options from a drop-down list. created by using two elements: and .
  • reset and submit buttons:
  • —– submit button allows the user to send the form data to the web server. specify the type attribute as “submit”.
  • —– reset button is used to reset the form data and will display any default values. specify the type attribute as “reset”.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

inline and block elements

A
  • block level elements will render on new lines in blocks by default
  • inline elements render within the line itself
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

CSS

A
  • cascading style sheets
  • language for styling HTML documents by specifying certain rules for layout and display in key/value pairs
  • simple and powerful method of allowing attachment of rendering information to HTML documents
  • used to style the webpages by setting background-color, font color, font size, font family, etc.
  • style rule composed of selectors and declarations

selectors: an HTML element
declarations: comprised of a property and a value surrounded by curly braces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

types of CSS

A
  • inline: contains the CSS property in the body section attached with element. specified within an HTML tag using style attribute.
  • internal / embedded: used when a single HTML document must be styled uniquely. CSS rule set should be within the HTML file in the head section
  • external: separate CSS file which contains only style property with the help of tag attributes. CSS property written in a separate file with .css extension and should be linked to the HTML document using link tag.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

element selector

A

selects HTML elements by their name / tag name like a, h1, div, p etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

CSS properties

A
  • border: allows to style the border area of a box. include “border-width”, “border-style”, “border-color”
  • padding: set the padding area for an element that separates its border from its content. can take up to 4 values.
  • margin: sets the margins around the sides of an element’s box. can take up to 4 values.
  • display: sets whether an element is treated as a block or inline elements and the layout used for its children, such as flow layout, flex or grid.
  • —- inline level elements: used to create a short structure that can have data and other inline elements. include <b>, <big>,< i>, <small>, <tt>, <abbr>, <acronym>, <code>, <strong>, etc.</strong></code></acronym></abbr></tt></small></big></b>
  • —- block level elements: used to create larger structures than inline elements also it starts on new lines by default. include <p>, </p><h1>, </h1><h2>, </h2><h3>, </h3><h4>, </h4><h5>,</h5><h6>, <ol>, </ol><ul>, </ul><pre>, <address>, <blockquote>, <dl>, <div>, , , <hr>, , etc .
  • position: defines how an element will be arranged on a page. property values are static, relative, absolute, fixed, or inherit.
  • color: used to specify the foreground color of text
  • text align: used to align the content inside the element. left, right, center, justify.</div></dl></blockquote></address></pre></h6></strong></code></acronym></abbr></tt></small></big></b>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

class selector

A
  • a name preceded by a period (“.”)

- uses the class attribute of an HTML element to match the specific HTML element

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

id selector

A
  • a name preceded by a hash character (“#”)
  • uses the id attribute of an HTML element to match the specific HTML element
  • id of an element should be unique within a page, so the id selector is used to select one unique element
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

amazon S3

A
  • object storage service that offers industry-leading scalability, data availability, security, and performance
  • store any type of file in S3
  • each individual object is put into a bucket, connect to Amazon S3 using a URL.
  • URL will have name of object and the name of bucket. The bucket is just the container to put objects in.
  • use REST API to connect to S3 using a URL.
  • browser does a HTTP PUT request and it puts the objects in the bucket.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

create AWS S3 bucket

A
  • bucket name: unique across all of Amazon S3, between 3 to 63 characters long, not contain uppercase characters, start with lowercase letter or number
  • uncheck “block public access” setting
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

JavaScript

A
  • ECMAScript
  • client-side scripting language
  • high-level, multi-paradigm, interpreted programming language used to create dynamic webpages
  • internal js: javascript code placed anywhere within the HTML page using tags
  • external js: JavaScript code placed in a separate file from the HTML code. files are saved with the “. js” extension and imported into the HTML page using the src attribute
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

JS syntax

A
  • comments: single line “//” or multi lines “/* */”
  • literals: fixed values. can be numbers, strings, boolean values, etc.
  • keywords: tokens that have special meaning in JavaScript. ex: break, case, catch, continue, do, else, finally, for, function, if, in, new, return, switch, this, throw, try, typeof, var, void, while, etc.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

JS variables

A
  • used to store data values
  • uses the var keyword to declare variables
  • starts only with the alphabet, underscores (_) or dollar ($)
  • cannot start with a number and also there shouldn’t be spaces in-between.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

JS operators

A
  • performs some operation on single or multiple operands and produces a result

Arithmetic operators - +, -, *, /, %, ++, –
Comparison Operators - ==, ===, !=, >, =, <=
Logical Operators - &&, ||, !
Assignment Operators - =, +=, -=, *=, /=, %=
Ternary Operator - ? : ;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

JS control flow

A

if/else if/else
for
for-in: allows iteration over the keys of any object
for-of: allows iteration over an array or array-like object
while
do-while

29
Q

JS compared to other languages (Java/C#)

A

JavaScript does not declare types, has no static type checking available, single-threaded and runs off of an event-loop, can run on a server or on a browser, is multi-paradigm language, utilizes prototype-based objects, class-based syntax

30
Q

JS data types

A

string
number: BigInt used to represent integers of arbitrary length. use n at end.
boolean
null: nothing
undefined: not initialized
object: set of key-value pairs. key is string, value can be any type.
Symbol

31
Q

== vs ===

A

== is used for comparison between two variables irrespective of the data type of variable.

=== is used for comparison between two variables but this will check strict type, which means it will check datatype and compare two values.

32
Q

type coercion

A

process of converting a value from one data type to another data type

explicit: can explicitly convert the datatype of the variable. For example: Number(‘3’), String (123), Boolean(2)
implicit: JavaScript is a loosely-typed language, values can also be converted between different types automatically. It usually happens when you apply operators to values of different types. For example: ‘3’ * ‘2’, 2/’5’, 123 + ‘’, 7 || ‘hello’, 123 != ‘456’

33
Q

truthy and falsy

A

falsy: any expressions or value that results in boolean false value
- - Obviously boolean false is false.
- - Any empty string will be evaluated to false.
- - Any undefined variable will be equal to false.
- - Any null variable will be equal to false.
- - Any numerical expression with result in NaN (not a number) will be equal to false.
- - Any numerical expression with result in zero will be equal to false.

truthy: any expressions or value that results in boolean true value

34
Q

variable scope

A

defines the lifetime and visibility of a variable

global: defined outside any function, block, or module, accessed everywhere in the application, lifetime is throughout the application, can declare the global variables in a browser using the global window object.
local:
- - function: variable declared in a function is only visible inside that function. var is the keyword to define variable for a function-scope accessibility. These variables cannot be accessed or modified.
- - block: scope of the variables declared inside the {} (curly brackets), use const and let keywords
- - lexical: variable defined outside a function can access the inside another function defined after the variable declaration. The inner functions are lexically bound to the execution context of their outer functions.

35
Q

hoisting

A
  • variable declarations made with var and function declarations made with the function keyword are hoisted - or moved - to the top of the scope in which they are declared when the JavaScript interpreter parses the code
  • means that variables and functions can be used before they are even declared
36
Q

let and const keywords

A

allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.
- value of a const variable can’t be changed through reassignment, and it can’t be redeclared.

37
Q

arrays in JS

A
  • a variable that allows the programmer to store more than one value
  • are objects and thus consist of key/value pairs and inherit from the Array prototype
  • array values can consist of JavaScript primitives, or other JavaScript objects, including arrays and functions.
  • created using square brackets
  • length of an array can be changed
  • remove elements using splice(), pop(), and shift
38
Q

array methods in JS

A

sort()
indexOf() & lastIndexOf()
find() & findIndex()
filter(): takes a callback function and creates a new array that is the made up of elements for which the callback function returns a truthy value. original array is not modified
map(): takes a callback function and creates a new array that is the result of calling the function on each element of the array. original array is not modified
reduce(): takes a callback function and returns a single value that is the result of calling the function for each value in the array

39
Q

template literals

A
  • provides an easy way to create multiline strings and perform string interpolation
  • strings that enclosed within the backtick character(`)
  • allow for embedded expressions (placeholders), which are indicated by the dollar sign and curly braces ($(expression}). These expressions can be used to evaluate code.
40
Q

tagged template

A
  • to parse template literals with a function.
  • ex. “tagFunctionHello ${firstName} ${lastName}!” does same as “tagFunction([‘Hello ‘, ‘ ‘, ‘!’], firstName, lastName)”
41
Q

raw strings

A
  • allows the accessing of raw strings as they were entered.
  • String.raw() is a built-in function which accepts a string literal argument and returns raw string. It returns the strings without any interpretation of backslashed characters.
42
Q

JS functions

A
  • defined using the function keyword
    syntax: function name(parameter1, parameter2, parameter3) {
    // code to be executed
    }
  • can return a value by executing the code after the function call. To return a value, we use the return keyword.
43
Q

pass by value

A
  • all function arguments are passed by value

primitives: primitive value is copied to a new variable
pbjects: value that is stored in a variable containing an object is not the object itself. Instead, an object reference is being stored inside of that variable.

44
Q

other JS functions

A
Function Expression / Anonymous Function: function declared without any identifier refer to it. It is an expression that the variable holds a function. For example: var x = function (a, b) {return a * b};
Self-Invoking Functions / IIFE Functions: an anonymous function that is invoked immediately after its definition. holds an anonymous function inside a set of parentheses (), which does the execution. Syntax : (function(){ code goes here...})();
Callback Functions: a function that gets executed after another function completes the execution. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors. use "callback" keyword as last parameter.
Closures: a function that remembers and accesses the variables and arguments of its outer function even after the function return. The closure able to access the variables defined between its curly brackets, the outer function’s variables and the global variables.
45
Q

JS “this” keyword

A

a reference variable that refers to the current object.

this alone: refers to a global Object.
this in function: refers to the Global object [object Window]
this in strict mode
this in Event Handlers: refers to the HTML element that received the event
this in Object Method Binding: refers to the object
The call() and apply() method: allows us to write a method that can be used on different objects.

46
Q

arrow functions

A
  • provides a concise way to write functions in JavaScript
    One-line arrow functions have implict return and defined without curly braces.
    Multiline arrow functions have multiple statements inside the function, enclosed with curly braces and need an explicit return to return something.
47
Q

strict mode

A
  • strictness of code
  • can be applied to function level in order to implement strictness only in that particular function.
  • does not allow us to use undefined variables, reserved keywords as variable or function name, duplicate properties of an object, duplicate parameters of the function, assign values to read-only properties, Modifying arguments object, and Deleting an undeletable property.
48
Q

Document Object Model (DOM) structure

A

tree-like hierarchical representation of the HTML document
- Each HTML element in the DOM tree is an object. The positions of the elements in the DOM tree are nodes.The tags are element nodes. Attributes in the elements are attribute nodes. The text inside elements is a text node. It may not have children and is always a leaf of the tree. The root of the DOM tree is a element, which is known as a document object.

49
Q

selecting elements from the DOM

A
  • by ID: getElementById() method is used to select an element based on its unique ID. will return the element as an object if the matching element was found, or null if no matching element was found in the document.
  • by Class Name: getElementsByClassName() method used to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names.
  • by Tag Name: getElementsByTagName() method used to select HTML elements by tag name. This method also returns an array-like object of all child elements with the given tag name.
  • with CSS Selectors: querySelector() and querySelectorAll() methods to select elements that matches the specified CSS selector. The querySelector() finds the first element that matches a CSS selector whereas the querySelectorAll() finds all elements that match a CSS selector.
50
Q

DOM manipulation

A
  • Create Elements: createElement() method is used to create a new element and attach it to the DOM tree
  • Replace Child Elements: replaceChild() method is used to remove an element from the DOM tree and insert a new one in its place.
  • Remove Child Elements: removeChild() method is used to remove an element from the DOM tree.
  • Append a Node: appendChild() method is used to add a node to the end of the list of child nodes of a specified parent node.
  • Insert a Node before another: insertBefore() method is used to insert a node before another node as a child node of a parent node.
  • Insert a Node After another: can insert a new node after an existing node as a child node, by selecting a parent node of the existing node and call the insertBefore() method on the parent node to insert a new node before that immediate sibling node.
  • Get or Set text of a Node: textContent property is used to get and set a text content inside a particular node.
  • Get or Set HTML of Element: innerHTML property to get the text and inner HTML elements inside a the particular element and the setting will replace the existing text and inner tags inside an element with the new content.
  • Clone a Node: cloneNode() method is used to clone an element. The cloneNode() method accepts an optional parameter. If the parameter value is true, then the original node and all of its descendants are cloned. If the parameter value is false, only the original node will be cloned.
51
Q

JS events

A

occur when user interaction takes place on a web page or is triggered by browser

onclick - This is a click event occurs when a user clicks the element on a web page.
ondblclick - This is a click event occurs when a user double clicks the element on a web page.
onload - This is a load event occurs when the browser has finished loading the page.
onunload - This is a load event occurs when a user closes the document.
onresize - This is a load event occurs when the browser window is minimized or maximized.
onmouseover - This is a mouse event occurs when the user moves the mouse over an HTML element.
onmouseout - This is a mouse event occurs when the user moves the mouse away from an HTML element
onkeydown - This is a keyboard event occurs when the user presses down a key on the keyboard
onkeyup - This is a keyboard event occurs when the user releases a key on the keyboard
onfocus - This is a form-input event occurs when the user gives focus to an element on a web page
onblur - This is a form-input event occurs when the user takes the focus away from a form element or a window
onchange - This is a form-input event that occurs when a user changes the value of a form element
onsubmit - This is a form-input event that occurs when the user submits a form on a web page.

52
Q

JS EventListener

A
  • a function in JavaScript that waits for an event to occur
  • addEventListener() function is an inbuilt function in JavaScript used to handle the event
    syntax: element.addEventListener(event, function, useCapture)
  • removeEventListener() method used to remove an event handler that has been attached with the addEventListener() method.
53
Q

event bubbling, event capturing

A

bubbling:

  • event propagates from the target element to its parents, then all its ancestors that are on the way to top.
  • Bottom to Top approach.

capturing:

  • event propagates from the top element to the target element.
  • Top to Bottom approach.
54
Q

traversing the DOM

A

Topmost nodes:

  • The document object is the root of every node in the DOM. The topmost tree nodes are associated with document properties:
    document. documentElement property - refers the DOM node of the tag.
    document. head property - refers the DOM node of the tag.
    document. body property - refers the DOM node of the tag.

Parent Nodes:
- The parent of any node is the node that is one level above in the DOM tree. There are two properties to get the parent — parentNode and parentElement.

Child Nodes:
- The children of a node are the nodes that are one level below it. The properties are listed below:
childNodes property - returns a list of child nodes, including text nodes.
firstChild property - give access to the first child node.
lastChild property - give access to the last child node.

Sibling Nodes:
- Siblings are nodes that are children of the same parent. The siblings of a node are any node on the same tree level in the DOM.
previousElementSibling property - give access to the previous sibling Node, i.e. the node that immediately precedes the specified node.
nextElementSibling property - give access to the next sibling vode, i.e. the node that immediately precedes or follows the specified node.

55
Q

JSON

A
  • A key value pair follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are separated by comma

applications:

  • Used to transmit data between the server and web application using JSON.
  • JSON format helps transmit and serialize all types of structured data.
  • Allows us to perform asynchronous data calls without the need to do a page refresh.
  • Web services and Restful APIs use the JSON format to get public data.
56
Q

AJAX (Asynchronous JavaScript And XML)

A
  • describes the process of exchanging data from a web server asynchronously with the help of XML, HTML, CSS, and JavaScript

work flow:

  1. A client event occurs on a webpage. (for example, the user clicks a button)
  2. JavaScript creates an XMLHttpRequest object.
  3. The XMLHttpRequest object makes an asynchronous request to the server.
  4. The server process the received HttpRequest.
  5. The server creates a response and sends data back to the browser.
  6. Browser process the returned data using JavaScript.
  7. The page content updated by javascript.
57
Q

XMLHttpRequest Object

A
  • is used to make HTTP requests to the server and receive data in response.
  • syntax to create XMLHttpRequest object: var xhttp = new XMLHttpRequest();
  • send request to server: open(method, URL, async), send()
  • server response:
  • —- responseText - Returns the response as a string.
  • —- responseXML - Returns the response as XML.
  • —- status - Returns the status as a number (For example, 200: “OK”, 403: “Forbidden”,404: “Page not found”)
  • —- statusText -Returns the status as a string (e.g., “Not Found” or “OK”).

the state of availability of data is given by the readyState attribute of XMLHttpRequest. The onreadystatechange function is called every time the readyState changes.
The readyState property defines the status of the XMLHttpRequest:
readyState = 0 : Not intialized
readyState = 1 : Connection establised
readyState = 2 : request received
readyState = 3 : processing request
readyState = 4 : request finished and response is ready

58
Q

working with JSON in Ajax

A
  • JSON in Request Payload: In JavaScript, to send a request using JSON data, we need to serialize our JSON object into a string. The JSON.stringify() method is used to converting an object to a string. Then, the server receives the string and process the request.
  • JSON in Response Body: If the response from the server is string/text, we need to parse them into a JSON object. The JSON.parse() method converts a JSON string representation to a JSON object.
  • XML in Response Body: The responseXML field contains the data as a read-only Document Object Model.
59
Q

promise

A
  • used to handle asynchronous operations in JavaScript.
  • constructor syntax: let promise = new Promise(function(resolve, reject) {
    // executor (the producing code, “singer”)
    });

The function passed to new Promise is called the executor. When a promise object is created, the executor runs automatically. It contains the code which produces the result. The arguments resolve and reject are callbacks.

When the executor obtains the result, it should call one of these callbacks:

resolve(value) — if the job finished successfully, with the result value.
reject(error) — if an error occurred, the error is the error object.
The Promise.status property, gives information about the state of the Promise object. The promise object can have three states: pending, fulfilled, and rejected.

A Promise object connects the executor and the consuming functions which will receive the result or error. Consuming functions can be registered using methods .then, .catch and .finally.

60
Q

Fetch API

A
  • provides a fetch() method defined on the window object. This method used to send requests and returns a Promise that retrieved from the response. Promise object represents a value that may not be available now but, will be resolved in the future.
  • syntax for fetch() method: let promise = fetch(url, [options])
  • handle errors: surround our await instruction with a try…catch block or to append a catch() callback to our promise

methods to access the response body in various formats:

response. text() – read the response and return as text.
response. json() – parse the response as JSON.
response. formData() – return the response as FormData object .
response. blob() – return the response as Blob (binary data with type).
response. arrayBuffer() – return the response as ArrayBuffer(low-level representation of binary data).

61
Q

async and await keywords

A

Async and Await are extensions of promises.

async -An async function is a function that operates asynchronously via the event loop, returns a Promise object implicitly. async ensures that the function returns a promise.

await - The await keyword is only valid inside async functions. await makes JavaScript wait until that promise settles and returns its result.

62
Q

HTTP Background, Requests, Responses

A

Background:

  • client-server protocol
  • Information is transferred via multiple messages
  • part of the application layer and thus requires some underlying communication protocol to transmit data- that protocol is TCP.

Requests:
Verb - Indicates the executing HTTP method.
URL - Specifies the endpoint where the resource is located.
HTTP Version.
Request Header - META-DATA (information) of the Request as key-value pairs such as format supported by the client, browser type, etc.
Request Body - Message content or resource representation.

Responses:
HTTP Response - Response Code. 200 (OK), 403 (Forbidden), 404 (Not Found), 500 (Internal Error), etc.
HTTP Version.
Response Header - META-DATA for the Response such as: content length, content type, date, etc.
Response Body - Some kind of payload in the case where HTTP is used in the context of a RESTful service then the body is a resource representation.

63
Q

Verbs

A
  • HTTP request verbs or methods indicate the action that a client hopes to perform.

characteristics of requests:
idempotent - “identical request can be made once or several times in a row with the same effect while leaving the server in the same state”- MDN
safe - doesn’t alter the server’s state. read-only
cacheable - Determines if there is a chance the response to the corresponding method can be cached
allowed in HTML forms
request has a body

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH
64
Q

status codes

A
Informational responses (100–199),
Successful responses (200–299),
Redirects (300–399),
Client errors (400–499),
Server errors (500–599)
65
Q

REST

A
  • Representational State Transfer.
  • for a web service to be RESTful it has to adhere to a set of guidelines or constraints
  • should not retain information about the state of the client.
  • defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state
  • the server creates an object or resource and returns the state of that object (the values contained within the object) when requested by the client.
66
Q

Resources and URLs in REST

A
  • resources in REST: information that can be named
  • resource representation: the particular state of the resource that is what is returned to a client of a restful service. format is in JSON or XML
  • resource identifier: make resources useful across the network and allow the client to request a resource’s representation
  • URL: a very frequently used form of resource identifier in a RESTful service

RESTful URL construction:
Whenever possible use nouns to name resources
Typically begin with the plural collection of a particular resource
Then use path parameters to identify a “singleton” resource in a specific document/record within a particular collection.
Capitalize on path structure to represent a heirarchy
Identify stores of resources that are managed by the client
Finally use query parameters to filter resources of a particular type.
/associates/{id}/projects?subject=java - /associates/{id}/projects?week=2

67
Q

Constraints of RESTful service

A

Interface Constraints:
Identification of resources
Manipulation of resources through representations
Self-descriptive messages
Hypermedia as the engine of application state

Client-Server:
“Separation of concerns”- the client focuses on the user interface and the server focuses on data storage. => Allows the two to develop separately/independent

Stateless:
The server should not retain any information about the state of the session.

Cacheable:
Responses should be explicitly labeled as cacheable or not. When the response is cached, the client may reuse the data in the response for later. This improves network efficiency.

Layered System:
The system should be organized into layers so that components can only communicate with components that are part of the same layer. It essentially provides some isolation to parts of the system.

68
Q

Exposing and Consuming RESTful API endpoints

A

Step 1 - Install the JSON Server using the npm install -g json-server command. JSON Server is available as a NPM package.
Step 2 - Create a new JSON file with name db.json. This file contains the JSON data which will be exposed by the REST API.
Step 3 - Running the JSON Server using the json-server –watch db.json command. We need to pass over the file name containing our JSON structure - db.json- as a parameter.
Step 4 - Now, we are going to test the REST API Endpoints exposed by the JSON Server with Postman.

69
Q

Rest with JSON

A
  • import Jackson library by adding dependencies to pom.xml file
  • create data class to act as resource
  • going to utilize the Jackson Object Mapper to create a JSON representation