Module 2 (4)
Module 2 (4)
➢ How JavaScript can access and update the contents of a web page in the browser
window.
• The DOM is neither part of HTML nor part of JavaScript, it is a separate set of rules.
➢ The DOM specifies the way in which the browser should structure this model using a
DOM tree. The DOM is called an object model because the model (the DOM tree) is
made of objects. Each object represents a different part of the page loaded in the
browser window.
➢ The DOM also defines methods and properties to access and update each object in this
model, which in turn updates what the user sees in the browser.
• When browser loads a web page, it creates a model of that page. The model is called a
DOM tree, and it is stored in the browsers' memory.
1. Document Node
2. Element Node
3. Attribute Node
4. Text Node
• Each node is an object with methods and properties. Scripts access and update this
DOM tree. Any changes made to the DOM tree are reflected in the browser.
• Example:
1. Document Node
• Every element, attribute, and piece of text in the HTML is represented by its own DOM
node. At the top of the tree a document node is added; it represents the entire page.
• When we access any element, attribute, or text node, we navigate to it via the document
node. It is the starting point for all visits to the DOM tree.
2. Element Nodes
• To access the DOM tree, we start by looking for elements. Once we find the element
we want, then we can access its text and attribute nodes.
3. Attribute Nodes
• The opening tags of HTML elements can carry attributes and these are represented by
attribute nodes in the DOM tree. They are part of that element.
• Once we access an element, there are specific JavaScript methods and properties to read
or change that element's attributes.
4. Text Nodes
• Once we have accessed an element node, we can then reach the text within that element.
This is stored in text node.
• Text nodes cannot have children. If an element contains text and another child element,
then child element is not a child of the text node but rather a child of the containing
element.
• Text node is always a new branch of the DOM tree, and no further branches come off
of it.
1. Locate the node that represents the element you want to work
Explanation
a. getElementById()
• Uses the value of an element’s id attribute.
b. querySelector()
• Uses a CSS selector, and returns the first matching element.
a. getElementsByClassName()
• Selects all elements that have a specific value for their class attribute.
b. getElementsByTagName()
• Selects all elements that have the specified tag name.
c. querySelectorAll()
• Uses a CSS selector to select all matching elements.
a. parentNode
b. previousSibling/nextSibling
c. firstChild/lastChild
d. appendChild()
e. removeChild()
• If script needs to use the same element(s) more than once, we can store the location of the
element(s) in a variable.
➢ This saves the browser looking through the DOM tree to find the same element(s)
again. It is known as caching the selection.
Here,
➢ itemOne does not store the <11> element, it stores a reference to where that node is
in the DOM tree.
➢ To access the text content of this element, we need to use the variable name:
itemOne.textContent
Accessing Elements
DOM queries could return one element or NodeList, which is collection of nodes.
• If a method returns more than one node then it will return a NodeList (which is
collection of nodes). Then we need to select the element we want from list using index
number.
• Evaluating the minimum number of nodes on the way to the element we want to work
with.
• Example: getElementById() will return one element but it can only be used when the
element we want to access has an id attribute.
1. getElementById('id')
➢ Selects an individual element given the value of its id attribute.
2. querySelector('css selector')
➢ Uses CSS selector syntax that would select one or more elements.
1. getElementsByClassName('class')
➢ Selects one or more elements given the value of their class attribute.
2. getElementsByTagName('tagName')
➢ Selects all elements on the page with the specified tag name.
3. querySelectorAll('css selector')
➢ Uses CSS selector syntax to select one or more elements and returns all of those
that match.
• It is the way to access an element because no two elements can share the same value
for their id attribute.
2. querySelector()
• It is very flexible because its parameter is a CSS selector, which means it can be
used to accurately target many more elements.
• First line of JavaScript code finds the element whose id attribute has a value of one, and
stores a reference to that node in a variable called el.
• The code then uses a property called className to update the value of the class attribute
of the element stored in this variable. Its value is cool, and this triggers a new rule in
the CSS that sets the background color of the element to aqua.
❖ Loop through each item in the NodeList and perform the same statements on each
of the element nodes.
❖ The length property tells how many items are in the NodeList.
• In a live NodeList, when script updates the page the NodeList is updated at the same
time. The methods beginning getElementsBy return live NodeLists. They are also faster
to generate than static NodeLists.
• In a static NodeList when script updates the page, the NodeList is not updated to reflect
the changes made by the script. The new methods that begin querySelector return static
NodeLists. They reflect the document when the query was made. If the script changes
the content of the page, the NodeList is not updated to reflect those changes.
1. getElementByTagName(‘h1’)
2. getElementByTagName(‘li’)
➢ This method returns four elements, one from each of the <li> elements on the page.
3. getElementByClassName(‘hot’)
➢ This NodeList contains only three of the <11> elements because we are searching for
elements by the value of their class attribute, not tag name.
4. querySelectorAll(‘li[id]’)
➢ This method returns four elements, one for each of the <li> elements on the page that
have an id attribute.
1. Item() Method
2. Array Syntax
1. Item Method
➢ We need to specify the index number of the element we want as a parameter of the
method.
2. Array Syntax
➢ We can access individual nodes using a square bracket syntax similar to accessing
individual items from an array.
➢ We need to specify the index number of the element we want inside square brackets
that follow the NodeList.
❖ The class name which is given in quotes within the parentheses after the method
name.
❖ Several elements can have the same value for their class attribute, this method
always returns a NodeList.
➢ The element name is specified as a parameter, and it is placed inside the parentheses
and is contained by quote marks.
Selecting Elements using CSS selectors
➢ querySelector() returns the first element node that matches the CSS-style selector.
➢ We could achieve this by using loop through each node in the collection and apply the
same statements to each.
Example:
➢ All of the statements inside the for loop's curly braces are applied to each element in
the NodeList one-by-one.
➢ To indicate which item of the NodeList is currently being worked with, the counter i is
used in the array-style syntax.
Looping through a NodeList
➢ It involves finding out how many items are there in the NodeList, and then setting a
counter to loop through them, one-by-one.
➢ Each time the loop runs, the script checks that the counter is less than the total number
of items in the NodeList.
Traversing the DOM
• Element node, can select another element in relation to it using these few properties.
This is known as traversing the DOM.
1. parentNode
• This property finds the element node for the containing (or parent) element in the
HTML.
• (1) If you started with the first <1i> element, then its parent node would be the one
representing the <ul> element.
2. previousSibling nextSibling
• These properties find the previous or next sibling of a node if there are siblings.
• If you started with the first <li> element, it would not have a previous sibling.
However, its next sibling (2) would be the node representing the second <li>.
3. firstChild lastChild
• These properties find the first or last child of the current element.
• If you started with the <ul> element, the first child would be the node representing
the first <li> element, and (3) the last child would be the last <11>.
Whitespace Nodes
• In case of whitespace nodes, Traversing the DOM can be difficult because some
browsers add a text node whenever they come across whitespace between elements.
Here,
• we can see all of the whitespace nodes added to the DOM tree for the list example.
• We could strip all the whitespace out of a page before serving it to the browser.
• One of the most popular ways to address this kind of problem is to use a JavaScript
library such as jQuery
1. Text Nodes
❖ The <em> element node has its own child text node which contains the word
fresh.
❖ The original text node is now a sibling of the node that represents the <em>
element.
➢ The first child of the <li> element is a text node, which contains the word six.
➢ In turn, that <em> element node has a child text node containing the word fresh.
➢ Finally, there is a text node holding the word figs, which is a sibling of both the text
node for the word "six" and the element node, <em>.
2. Containing Element
• These properties update the content of an element, the new content will overwrite the
entire contents of the element
• Example
➢ By using any of these properties to update the content of the <body> element, it
would update the entire web page.
• By selecting a text node, we can retrieve or modify the content of it using the nodeValue
property.
1. The <11> element node is selected using the getElementById() method.
4. We have the text node and can access its contents using nodeValue.
• First the element node is accessed and then its text node.
• The text node has a property called nodeValue which returns the text in that text node.
• We can also use the nodeValue property to update the content of a text node.
• Example:
• The textContent property collects or updates the text that is in the containing element
(and its children). The textContent property on element returns the value. We can use
this property to update the content of the element; it replaces the entire content of it
(including any markup).
• Example:
<li id = “one”><em>fresh</em>figs</li>
document.getElementById(‘one’).textContent;
Accessing Text Only
• The script gets the content of the first list item using both the textContent property and
innerText and then writes the values after the list.
• Later the value of the first list item is then updated using the textContent property.
• There are two different ways to add or remove content from a DOM tree
1. innerHTML property
2. DOM manipulation
Access & Update Text & Markup with innerHTML
• When getting HTML from an element, the innerHTML property will get the content of
an element and return it as one long string, including any markup that the element
contains.
• When used to set new content for an element, it will take a string that can contain
markup and process that string, adding any elements within it to the DOM tree.
Example:
• <li id =“one”><em>fresh</em>figs</li>
Get Content
• Code collects the content of the list item and adds it to a variable.
Set Content
• Code adds the content of the elContent variable to the first list item
document.getElementById('one').innerHTML = elContent;
Update Text & Markup
• Here we need to retrieve the content list item and stores it in a variable.
1. createElement()
• Create a new element node using the createElement() method and this element node is
stored in a variable.
2. createTextNode()
• Create a new text node using createTextNode() and this node is stored in a variable.
• It can be added to the element node using the appendChild() method. This provides the
content for the element.
3. appendChild()
• The appendChild() method allows us to specify which element we want this node added
to, as a child of it.
• This new element is stored inside a variable until it is attached to the DOM tree.
• createTextNode() creates a new text node to attach to an element.
• Example:
• Select the element that is going to be removed and store the element node in a variable.
• Find the parent element that contains the element that we want to remove and store the
element node in a variable.
• removeChild() method takes one parameter: the reference to the element that we no
longer want.
• removeChild() method is used on the variable that holds the container node.
1. document.write()
• Advantages
➢ It is a quick and easy way to show beginners how content can be added to a page.
• Disadvantages
It can cause problems with XHTML pages that are strictly validated.
2. element.innerHTML
• innerHTML property get/update the entire content of any element (including markup)
as a string.
• Advantages
➢ You can use it to add a lot of new markup using less code than DOM manipulation
methods.
➢ It can be faster than DOM manipulation when adding a lot of new elements to a
web page.
➢ It should not be used to add content that has come from a user as it can cause security
risk.
➢ It can be difficult to isolate single elements that we want to update within a larger
DOM fragment.
3. DOM Manipulation
• DOM manipulation refers to using a set of methods and properties to access, create,
and update elements and text nodes.
• Advantages
➢ It is suited to changing one element from a DOM fragment where there are many
siblings.
• Disadvantages
➢ If you have to make a lot of changes to the content of a page, it is slower than
innerHTML.
➢ You need to write more code to achieve the same thing compared with innerHTML.
• For example:
➢ website's cookies
➢ Session tokens: information that identifies you from other users when you log
into a site
• Malicious code often mixes HTML and JavaScript (although URLS and CSS can be
used to trigger XSS attacks).
• Example:
• Below code stores cookie data in a variable, which could then be sent to a third-party
server:
1. Only let visitors input the kind of characters they need to when supplying information.
This is known as validation. Do not allow untrusted users to submit HTML markup or
JavaScript.
3. The database may contain markup and script from trusted sources (e.g., your content
management system). This is because it does not try to process the code; it just stores
it.
4. As your data leaves the database, all potentially dangerous characters should be escaped
5. Make sure that you are only inserting content generated by users into certain parts of
the template files.
6. Do not create DOM fragments containing HTML from untrusted sources. It should only
be added as text once it has been escaped.
• Prevent users from entering characters into form fields that they do not need to use
when providing information.
• Example, user names and email addresses will not contain angled brackets, ampersands,
or parentheses, so we can validate data to prevent characters like this being used.
• Malicious code can live in an event handler attribute without being wrapped in <script>
tags.
• Browsers process HTML, CSS, and JavaScript in different ways (or execution
contexts), and in each language different characters can cause problems. Therefore, we
should only add content from untrusted sources as text (not markup), and place that text
in elements that are visible in the viewport.
XSS: Escaping & Controlling Markup
• Any content generated by users that contain characters that are used in code should be
escaped on the server.
• All data from untrusted sources should be escaped on the server before it is shown on
the page.
1. HTML
2. Javascript
3. URL’s
• For links containing user input (e.g., links to a user profile or search queries), use the
JavaScript encodeURIComponent() method to encode the user input.
, /? : @ & = + $ #
• When you add untrusted content to an HTML page then, it should still be added to the
page as text.
Javascript
Jquery
❖ Do use: .text())
Attribute Nodes
• hasAttribute() method of any element node checks if an attribute exists. The attribute
name is given as an argument in the parentheses.
• Using hasAttribute() in an if statement like this means that the code inside the curly
braces will run only if the attribute exists on the given element.
Creating Attributes & Changing Their Values
• The className property allows us to change the value of the class attribute.
➢ If the attribute does not exist, it will be created and given the specified value.
➢ It takes two parameters: the attribute name, and the value for the attribute.
Removing Attributes
• To remove an attribute from an element, first select the element, then call
removeAttribute(). It takes one parameter: the name of the attribute to remove.
• getElementById() method is used to retrieve the first item from this list, which has an
id attribute with a value of one.
Example: Document Object Model
• Adding an item to the start of a list requires the use of a different method than adding
an element to the end of the list.
• This involves looping through each of the <li> elements and updating the value of the
class attribute.
• Events occur when users click or tap a link or swipe over a element or keyboard type, etc
1. Select the element node(s) you want the script to respond to.
For example, if you want to trigger a function when a user clicks on a specific link, you
need to get the DOM node for that link element. You do this using a DOM query.
2. Indicate which event on the selected node(s) will trigger the response.
Programmers call this binding an event to a DOM node.
3. State the code you want to run when the event occurs. When the event occurs, on a
specified element, it will trigger a function. This may be a named or an anonymous
function.
Example:
Three ways to bind an event to an element
• In the HTML, the first <input> element has an attribute called onblur (triggered when
the user leaves the element).
• The value of the attribute is the name of the function that it should trigger.
• Often it would call a function that was written either in the <head> element or a separate
JavaScript file .
2. Traditional DOM Event Handlers
• When using event handlers, the event name is preceded by the word "on" (onsubmit,
onchange, onfocus, onblur, onmouseover, onmouseout, etc).
• Example:
Here,
➢ Named function is written first when event fires on the DOM node.
➢ Event handler elUsername.onblur indicates code is waiting for blur event to fire on the
element stored in the variable called elUsername.
Event Listeners
• They handle events, which can deal with more than one function at a time.
• Syntax:
• In event handler, we want to wait until the event triggers it and we cannot have parentheses
after the function names in event handles or listeners and passing arguments requires a
workaround
• Example
Here,
• The first line in checkUsername() function the minLength parameter specifies the
minimum number of characters that the username should be.
• To receive this information, the event listener uses an anonymous function, which acts
like a wrapper. Inside that wrapper the checkUsername() function is called, and passed an
argument.
Here,
❖ If the browser supports the addEventListener() method, the code inside the first set of
curly braces is run using addEventListener().
❖ If it is not supported, then the browser will use the attachEvent() method that older
versions of IE will understand. In the IE version, note that the event name must be
preceded by the word "on."
Event Flow
• The order in which event fire is known as event flow and events flow in two directions.
• The flow of events matters when our code has event handlers on an element and one of
its ancestor or descendant elements.
Event Object
• Event object tells us information about the event, and the element it happened upon.
• Every time an event fires, the event object contains helpful data about the event, such
as:
• The event object is passed to any function that is the event handler or listener.
• If you need to pass arguments to a named function, the event object will first be passed
to the anonymous wrapper function.
Event Object in IE5-8
• In lower version of IE, event object is not passed automatically to event handler/ listener
functions but it is available as child of the window object.
• Example:
Here, to get properties, we need to use
Var target;
Target = e.target || e.srcElement;
• Example:
1. The function is called checkLength() can be used on any text input.
3. In order to determine which element, the user was interacting with, the function uses
the event object's target property.
Event Delegation
• Example:
➢ If we place the event listener on the <ul> element rather than on links in each <li>
element, we only need one event listener.
➢ And if you add or remove items from the list it would still work the same.
1. preventDefault()
• Some events, such as clicking on links and submitting forms, take the user to another
page. To prevent the default behavior of such elements (e.g., to keep the user on the
same page rather than following a link or being taken to a new page after submitting a
form), we can use the event object's preventDefault() method.
• Example:
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
2. stopPropagation()
• To stop the event bubbling up, we can use the event object's stopPropogation () method.
if (event.stopPropogation) {
event.stopPropogation();
} else {
}
event.cancel Bubble = true;
• It prevents the default behavior of the element, and prevents the event from bubbling
up or capturing further.
➢ Because the owner of the function is no longer the element that the event listener
was bound to, it is an anonymous function.
2. HTML5 Events
• The HTML5 specification details events that browsers are expected to support
that are specifically used with HTML.
• For example, events that are fired when a form is submitted or form elements
are changed like submit, input, change, Readystatechange,
DOMContentLoaded, hashchange
3. BOM Events
❖ touchstart
❖ touchend
❖ touchmove
❖ orientationchange
• User interface (UI) events occur as a result of interaction with the browser window.
• The event handler/listener for Ul events should be attached to the browser window.
Load
• The load event is used to trigger scripts that access the contents of the page.
• Load event only fires when everything else on the page has loaded (images, scripts,
etc)
• Example,
❖ A function called setup() gives focus to the text input when the page has loaded.
❖ The event is automatically raised by the window object when a page has finished
loading the HTML and all of its resources: images, CSS.
❖ The setup() function would not work before the page has loaded because it relies on
finding the element whose id attribute has a value of username, in order to give it
focus.
Focus & Blur Events
• The HTML elements we interact with, such as links and form elements, can gain focus.
• The focus and blur events are most commonly used on forms.
❖ We need to trigger form validation as a user moves from one control to the next.
Example
Mouse Events
• They are fired when the mouse is moved and also when its button are clicked.
Click Events
• Event object can tell where the cursor was positioned when an event was triggered.
Determining Position
• As we move our mouse around the screen, the text inputs across the top of the page are
updated with the current mouse position.
• This demonstrates the three different positions we can retrieve when the mouse is
moved or when one of the buttons is clicked.
Keyboard Events
• The event object has a property called keyCode, which can be used to tell which key was
pressed.
➢ The event listener checks for the keypress event on the <textarea> element.
➢ Each time it fires, the charCount() function updates the character count and shows
the last character used.
Form Events
• Whenever elements are added to or removed from the DOM, its structure changes. This
change triggers a mutation event.
• When your script adds or removes content from a page it is updating the DOM tree.
• Below are some events that are triggered when the DOM changes and they are already
scheduled to be replaced by an alternative called mutation observers.
➢ If our script makes a lot of changes to a page, we end up with a lot of mutation
events firing. This can make a page feel slow or unresponsive.
➢ Mutation observers are designed to wait until a script has finished its task before
reacting, then report the changes as a batch.
Using Mutation Events
• First listens when user clicks the link to add new list item.
• Second waits for the DOM tree within the <ul> element to change.
HTML5 Events
• If users leave the page before they press the submit button, the beforeunload event
checks that they want to leave.
• Example Events
• Example Events
Introduction to MERN
• Any web application is built using multiple technologies and combinations of these
technologies is called a “stack”.
• MEAN (MongoDB, Express, AngularJS, Node.js) stack was one of the early open-
source stacks.
• MERN (MongoDB, Express, React, Node.js) pre-built technology stack based on
JavaScript technologies.
MERN Components
1. React
• Facebook folks built React for their own use, and later they made it open-source.
❖ Being declarative makes the views consistent, predictable, easier to maintain, and
simpler to understand.
• A React component declares how the view looks, given the data.
❖ We declare how the view looks and React builds a virtual representation, an in-
memory data structure.
• When things change, React builds a new virtual DOM based on the new truth (state)
and compares it with the old (before things changed) virtual DOM.
❖ React then computes the differences in the old and the changed Virtual DOM,
then applies these changes to the actual DOM.
• The fundamental building block of React is a component that maintains its own state
and renders itself.
• A component encapsulates the state of data and the view, or how it is rendered.
• Components talk to each other by sharing state information in the form of read-only
properties to their child components and by callbacks to their parent components.
❖ This lets you create nested DOM elements in a familiar language rather than
hand-construct them using JavaScript functions.
2. Node.js
• Node.js Modules - Node.js uses its own module system based on CommonJS to put
together multiple JavaScript files.
• We can include the functionality of another JavaScript file by using the require
keyword.
• Node.js ships with a bunch of core modules compiled into the binary. These modules
provide access to the operating system elements such as the file system, networking,
input/output, etc.
• We can use npm to install third-party libraries (packages) and manage dependencies
between them.
❖ Node.js, has no threads. It relies on callbacks to let you know that a pending task
is completed.
❖ This is nothing but a queue of events that need to be processed, and callbacks to
be run on those events.
3. Express
• Express is a framework that simplifies the task of writing the server code.
• The Express framework lets define routes, specifications when an HTTP request
matching a certain pattern arrives.
❖ Express parses the request URL, headers, and parameters for you.
4. MongoDB
5. NoSQL
1. First is their ability to horizontally scale by distributing the load over multiple
servers.
2. Second aspect is that NoSQL databases are not necessarily relational databases.
Document-Oriented
JavaScript Base
• MongoDB comes with a shell that’s built on top of a JavaScript runtime like Node.js
to interact with the database via command line.
1. React-Router
• It is similar to server-side routing that Express does: a URL is parsed and based on
its components; a piece of code is associated with the URL.
• React-Router also manages the browser’s Back button functionality so that we can
transition between what seem as pages without loading the entire page from the
server.
2. React-Bootstrap
• Bootstrap, the most popular CSS framework, has been adapted to React and the
project is called ReactBootstrap.
• This library not only gives us most of the Bootstrap functionality, but the
components and widgets provided by this library gives information on how to
design our own widgets and components
3. Webpack
• We will be using Webpack to modularize and build the client-side code into a
bundle to deliver to the browser, and also to “compile” some code.
Other Libraries
1. Redux:
• This is a state management library that also combines the Flux programming
pattern.
• It’s typically used in larger projects where even for a single screen, managing the
state becomes complex.
2. Mongoose
• This library adds a level of abstraction over the MongoDB database layer and lets
the developer see objects as such.
• The library also provides other useful conveniences when dealing with the
MongoDB database.
3. Jest
• This is a testing library that can be used to test React applications easily.
Versions
Why MERN
1. JavaScript Everywhere
❖ They need to be run on the client side so that user experience is better by
being more responsive to user inputs.
❖ They also need to be run on the server side to protect the data model
2. JSON Everywhere
• JSON could be used in the database, or in the application server or in the client side
and this saves a lot of data transformation code.
3. Node.js Performance
• npm is easiest to use and fastest package manager because npm packages are small,
due to the compact nature of JavaScript code.
6. Isomorphic
• Means the web app is made of code that can be rendered on both server and client
side.
• React runs on JavaScript, which is the same on the client or the server.
➢ When React-based code runs on the browser, it gets data from the server and
constructs the page (DOM) in the browser. This is the SPA way of rendering the
UI.
➢ When React-based code is used to get the data from an API server and construct the
page (HTML) and stream that back to the client. This is called server-side rendering
(SSR)
Hello World
• Hello World application, we’ll use React to render a simple page and use Node.js and
Express to serve that page from a web server.
• React library is available as a JavaScript file that we can include in the HTML file using
the <script> tag.
1. React core module, the one that is responsible for dealing with React components,
their state manipulation, etc.
2. ReactDOM module, which deals with converting React components to a DOM that
a browser can understand.
• These two libraries can be found in unpkg, a Content Delivery Network (CDN)
• Create a <div> that will eventually hold any React elements that we will create.
• This can be an empty, but it needs an ID, say, content, to identify and get a handle in
the JavaScript code.
• To create the React element, the createElement() function of the React module needs
to be called.
Here,
• The last parameter(s) is zero or more children elements, which again are created
using the createElement() function itself.
• It resides in the JavaScript engine’s memory as a deeply nested set of React elements,
which are also JavaScript objects
• Each of these React elements needs to be transferred to the real DOM for the user
interface to be constructed on screen.
• This function takes in as arguments the element that needs to be rendered and the DOM
element that it needs to be placed under.
• Let's put all this together in index.html. The contents of this file is shown below
JSX
• React has a markup language called JSX, which stands for JavaScript XML.
• JSX can be used to construct an element or an element hierarchy and make it look very
much like HTML instead of the React.createElement() calls.
• Example:
nvm
• This tool makes installation and switching between multiple versions of Node.js easy
• To install nvm,
❖ Windows users can follow nvm for Windows (search for it in search engine) or
install Node.js directly without nvm.
Node.js
$ nvm install 10
• We can confirm the version of node that's been installed
$ node –version
$ npm –version
Npm
Express
• require is a JavaScript keyword specific to Node.js, and this is used to import other
modules.
• An Express application is web server that listens on a specific IP address and port.
• Below code instantiate the one and only application by calling the express() function:
• Express is a framework gets most of the job done by functions called middleware. A
middleware is a function that takes in an HTTP request and response object, plus the
next middleware function in the chain.
• The built-in express.static function generates a middleware function
• The argument to the static() function is the directory where the middleware should
look for the files
• for the application to use the static middleware, we need to mount it on the
application.
app.use('/', fileServerMiddleware);
• first argument to this method is the base URL of any HTTP request to match.
• The listen() method of the application starts the server and waits forever for requests.
It takes in a port number as the first argument
app.listen(3000, function () {
console.log('App started on port 3000’);
});
• Below is the final server code, with the use() call merged with the creation of the
middleware in a single line, and skipping the optional first argument, the mount point
• To start the server, run it using the Node.js runtime like below
$ node server.js
• To start the server, we had to supply the name of the entry point
$ npm start
• We need to separate out the JSX and JavaScript from the all-in-one index.html and refer
to it as an external script.
• Let’s replace the inline script with a reference to an external source like this
• Index.html
JSX Transform
• Create a new directory to keep all the JSX files, which will be transformed into plain
JavaScript and into the public folder.