Emerging Trends and Technologies - Introduction to Full Stack Web Development PDF
Document Details
Tags
Summary
This document provides a summary of emerging web development trends, focusing on the introduction to full-stack web development. It outlines the components of full-stack development, front-end technologies like HTML, CSS, JavaScript, and frameworks like React, backend technologies such as Node.js and Express.js, and databases.
Full Transcript
EMERGING TRENDS AND TECHNOLOGIES UNIT-1 INTRODUCTION TO FULL STACK WEB DEVELOPMENT 1.1 INTRODUCTION TO FULL STACK DEVELOPMENT Full stack development: It refers to the development of both front-end (client side) and back-end (server side)...
EMERGING TRENDS AND TECHNOLOGIES UNIT-1 INTRODUCTION TO FULL STACK WEB DEVELOPMENT 1.1 INTRODUCTION TO FULL STACK DEVELOPMENT Full stack development: It refers to the development of both front-end (client side) and back-end (server side) portions of web applications. Full stack web Developers: Full stack web developers can design complete web applications and websites. They work on the frontend, backend, database, and debugging of web applications or websites. 1.2 OVERVIEW OF FULL STACK AND PRE-REQUISITES Full stack development: It refers to the development of both front-end(client side) and back-end (server side) portions of web application. Full stack web Developers: Full stack web developers can design complete web applications and websites. They work on the frontend, backend, database, and debugging of web applications or websites. 1.2.1 What is Frontend Web Development? Front-end web development is the process of developing the client side of the web application wherein the focus is on the users. The full-stack developer with users in mind undertakes this process to develop a website that is easy to use and interact with. The developer in this process focuses on the visual elements of the application. It is also the responsibility of the developer in front-end development to ensure that the website or application runs smoothly. Front-end development focuses on elements like: 1. Images 2. Graphics 3. Animations 4. Layouts 5. Content organization 6. Navigation 1.2.2 What is Backend Web Development? Back-end web development refers to the process of developing the server side of the website, i.e., the side that users cannot see or interact with. The main aim of back-end development is to make the website interactive and easy to use. During the back-end development process, developers emphasized on: 1. Building the code EMERGING TRENDS AND TECHNOLOGIES 2. Database management 3. Debugging or troubleshooting the website or application 4. Application programming interfaces 5. Architecture Therefore, front-end and back-end development are distinct from each other in terms of the sides of the website application they focus on. However, the two work together to create a dynamic and attractive website that provides users with an immersive experience when browsing. 1.2.3 Front-end Languages and Frameworks HTML and CSS HTML short for Hypertext markup language governs the appearance of text/images on the screen. It formats the text as headings, paragraphs, pop-ups, and so on. It typically consists of tags that give a different meaning to the text in a document structure. CSS (Cascading Style Sheets) is a style sheet that allows you to alter and style different web components for font, size, spacing, etc. It makes the content on the webpage more decorative. EMERGING TRENDS AND TECHNOLOGIES JavaScript It is a powerful client-side programming language mainly used for enhancing user interaction with the application. It offers several libraries and frameworks like React, Angular, Vue, and JQuery. A full-stack developer needs to be proficient in one or more of these tools. 1.2.4 Backend Technologies and Frameworks JavaScript and its environments like Node JS and Express JS are an open-source, cross-platform runtime environment that allows developers to create server-side tools and JavaScript applications. Knowledge of the basic command line like npm (Node Package Manager) is essential. Java, in particular, was built from the ground up to be run on the server side. Popular Java frameworks include Spring and Java Server faces. Python is the most popularly used language. It is flexible and easy to use. We use Python frameworks like Django and Flask for backend development. Django is a high-level Python web framework that enables the rapid development of websites. It is free and open-source and has a huge and active community of users. C# language is for many the most preferred architecture when it comes to backend programming in Windows environments. Other languages include PHP, Perl, and Ruby. Database Management Systems A full-stack developer writes code to perform Relational mapping to fetch data from the database. MySQL, SQL SERVER, Oracle Database, PostgreSQL, and MongoDB are popularly used DBMS. EMERGING TRENDS AND TECHNOLOGIES Version Control Version control systems help to manage the project files and keep track of the entire history of the user's things. Popular ones are Git, GitHub, and Subversion. Git helps to manage the project files. It keeps track of the entire history of things that the user is working on. GitHub is a web-based service for version control using Git. The user can look at other people’s code, identify issues or errors, and even propose changes. Web Hosting Platforms Web hosting platforms allow you to deploy your product on a cloud service provider so we can access it from the WWW. Popular ones are Amazon web services, Google Cloud Platform, Heroku, and Microsoft Azure. Soft Skills A full-stack developer needs to possess some basic soft skills as well. Creativity: The developer must understand the project's objectives and create a product that engages the target audience. Strategic planning: Planning is a critical phase in any development life-cycle. The developer should possess the aptitude to plan the design, development, and implementation phases strategically. This helps streamline the process. Analytical skills: As the name suggests, these skill helps to analyze information accurately and make logical, data-driven decisions that help in maximizing efficiency. Now, these are skills that one develops when they're exposed to them. But a good sense of understanding is required. Problem-solving skills are again crucial to predicting any errors and developing a bug-free application. From a business perspective, problem-solving skills play a significant role in ensuring the smooth conduction of tasks. Time management skills: The developer must meet the deadlines while ensuring the proper execution of his tasks. 1.3 Arrow Function Arrow functions were introduced in ES6. Arrow functions allow us to write a shorter function syntax: let myFunction = (a, b) => a * b; EMERGING TRENDS AND TECHNOLOGIES Arrow Function with no parameter Example let hello = ""; hello = () => { return "Hello World!"; } document.getElementById("demo").innerHTML = hello(); Output Hello World! Arrow Function with one parameter let hello = ""; hello = (val) => "Hello " + val; document.getElementById("demo").innerHTML = hello("Universe!"); OUTPUT: Hello Universe! EMERGING TRENDS AND TECHNOLOGIES Arrow Function with Two parameter let hello = ""; hello = (a,b) => a + b; document.getElementById("demo").innerHTML = hello(4,3); OUTPUT: 7 JavaScript Map map() creates a new array from calling a function for every array element. It does not execute the function for empty elements or change the original array. JavaScript Map is a collection of key-value pairs, enabling efficient data retrieval and manipulation. On iterating a map object returns the key, and value pair in the same order as inserted. Map() constructor is used to create Map in JavaScript. JavaScript Map has a property that represents the size of the map. Example: // Input array let arr = [2, 5, 6, 3, 8, 9]; // Using map to transform elements let newArr = arr.map(function (val, index) { return { key: index, value: val * val }; }) // Display output console.log(newArr) EMERGING TRENDS AND TECHNOLOGIES Output: [ { key: 0, value: 4 }, { key: 1, value: 25 }, { key: 2, value: 36 }, { key: 3, value: 9 }, { key: 4, value: 64 }, { key: 5, value: 81 } ] Example: let users = [ {firstName : "Susan", lastName: "Steward"}, {firstName : "Daniel", lastName: "Longbottom"}, {firstName : "Jacob", lastName: "Black"} ]; let userFullnames = users.map(function(element){ return `${element.firstName} ${element.lastName}`; }) console.log(userFullnames); Output: [ 'Susan Steward', 'Daniel Longbottom', 'Jacob Black' ] 1.4 Installation for React Facebook developed React JS. React.js is an open-source component-based front-end JavaScript library. It is used to create fast and interactive user interfaces for web and mobile applications. It is easy to create a dynamic application in React because it requires less coding and offers more functionality. It is used by big MNCs and fresh new startups. Features of React: Reusable Components: A single React app consists of many components each component has its own logic and code but we can easily reuse components any number of times hence reducing the developer's time and increasing the efficiency of work. Debugging: React app can be easily debugged using “react developer tools”. It’s a browser extension that can be used for both Chrome as well as Firefox. EMERGING TRENDS AND TECHNOLOGIES Installation React.js on Windows: Step 1: Install Node.js installer for Windows. Once downloaded open NodeJS without disturbing other settings, and click on the Next button until it’s completely installed. Install the 14.18.1 LTS Step 2: Open the command prompt to check whether it is completely installed or not type the command –> node -v. EMERGING TRENDS AND TECHNOLOGIES If the installation went well it will give you the version you have installed Now, Check whether the node package manager is installed completely or not, to check npm is installed or not you have to type the command: npm -v It will give you npm version which is installed on your device. 1.6 Create a new React App npm install -g create-react-app Installation will take a few seconds It will globally install the react app for you. To check everything went well run the command create-react-app --version EMERGING TRENDS AND TECHNOLOGIES version 4.0.3 If everything goes well it will give you the installed version of the React app Step 4: Now Create a new folder where you want to make your react app using the below command: mkdir Move inside the same folder using the below command: cd new folder (your folder name) EMERGING TRENDS AND TECHNOLOGIES Step 5: Now inside this folder run the command –> create-react-app react first YOUR_APP_NAME It will take some time to install the required dependencies NOTE: Due to npm naming restrictions, names can no longer contain capital letters, thus type your app’s name in lowercase. EMERGING TRENDS AND TECHNOLOGIES Step 6: Now open the IDE of your choice for Visual Studio code and open the folder where you have installed the react app new folder inside the folder you will see your app’s name reactapp (In our example). Use the terminal and move inside your app name folder. Use the command cd reactapp (your app name) Step 7: To start your app run the below command: npm start EMERGING TRENDS AND TECHNOLOGIES Once you run the above command a new tab will open in your browser showing the React logo as shown below: Congratulations you have successfully installed the react-app and are ready to build awesome websites. 1.6 JSX The render function specifies the HTML output of a React component. JSX (JavaScript Extension), is a React extension that allows writing JavaScript code that looks like HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like Babel) to transform HTML-like syntax into standard JavaScript objects that a JavaScript engine will parse. JSX allows you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then the preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children. Why use JSX? It is faster than regular JavaScript because it performs optimization while translating the code to JavaScript. Instead of separating technologies by putting markup and logic in separate files, React uses components that contain both. We will learn components in a further section. It is type-safe, and most of the errors can be found at compilation time. It makes it easier to create templates. Nested Elements in JSX EMERGING TRENDS AND TECHNOLOGIES To use more than one element, you need to wrap it with one container element. Here, we use div as a container element which has three nested elements inside it. 1.7.1 JSX Attributes JSX uses attributes with the HTML elements the same as regular HTML. JSX uses a camelCase naming convention for attributes rather than the standard naming convention of HTML such as a class in HTML becomes a class Name in JSX because the class is the reserved keyword in JavaScript. We can also use our custom attributes in JSX. For custom attributes, we need to use the data- prefix. In the below example, we have used a custom attribute data-demo Attribute as an attribute for the tag. Example import React, { Component } from 'react'; class App extends Component{ render(){ return( hello world hello world1 ); } } export default App; Example hello world hello world1 EMERGING TRENDS AND TECHNOLOGIES UNIT-2 REACT BASICS 2.1 DIFFERENT COMPONENTS 2.1.1 Class Component Before React 16.8, Class components were the only way to track the state and lifecycle of a React component. Function components were considered "stateless". With the addition of Hooks, Function components are now almost equivalent to Class components. The differences are so minor that you will probably never need to use a Class component in React. Even though Function components are preferred, there are no current plans to remove Class components from React. Example Header.js import React from "react"; class Header extends React.Component { render() { return( Diploma Computer /It Engineering ; ); } } export default Header; App.js import './App.css'; import Header from './Header'; function App() { return ( ); } export default App; EMERGING TRENDS AND TECHNOLOGIES Output: Diploma Computer/It Engineering. 2.1.2 Function component A React functional component is a straight JavaScript function that takes props and returns a React element. Writing functional components has been the traditional way of writing React components in advanced applications since the advent of React Hooks. A React component’s primary function is to classify the displayed view and connect it to the code that governs its actions. React’s functional components reduce this to the most basic profile feasible: a function that accepts properties and returns a JSX definition. The function body contains all of the definitions needed for actions, and the class-related sections of object-oriented components are omitted. Example Header.js import React from 'react' import './App.css'; function Header() { return ( My First Functional Component ); } export default Header; App.js import './App.css'; import Header from './Header'; function App() { return ( ); } export default App; Output: My First Functional Component EMERGING TRENDS AND TECHNOLOGIES 2.2 PROPS Props stand for "Properties." They are read-only components. It is an object that stores the value of attributes of a tag and works similarly to the HTML attributes. It gives a way to pass data from one component to other components. It is similar to function arguments. Props are passed to the component in the same way as arguments passed in a function. Props are immutable so we cannot modify the props from inside the component. Inside the components, we can add attributes called props. These attributes are available in the component as this.props and can be used to render dynamic data in our render method. When you need immutable data in the component, you have to add props to reactDom.render() method in the main.js file of your ReactJS project and use it inside the component that you need. It can be explained in the below example. Example Create a variable named carName and send it to the Cars component: Cars.js import React from 'react'; function Car(props) { return I am an {props.brand}!; } function Cars() { const carName = "Audi"; return ( Describe how the vehicle looks and runs ); } export default Cars; App.js import './App.css'; import Cars from './Cars'; function App() { return ( EMERGING TRENDS AND TECHNOLOGIES ); } export default App; Output: Describe how the vehicle looks and runs I am an Audi! 2.3 STATE The state is an updatable structure that is used to contain data or information about the component. The state of a component can change over time. The change in state over time can happen as a response to user action or system event. A component with a state is known as a stateful component. It is the heart of the react component that determines the behaviour of the component and how it will render. They are also responsible for making a component dynamic and interactive. A state must be kept as simple as possible. It can be set by using the setState() method and calling setState() method triggers UI updates. A state represents the component's local state or information. It can only be accessed or modified inside the component or by the component directly. To set an initial state before any interaction occurs, we need to use the getInitialState() method. Defining the state To define a state, you have to first declare a default set of values for defining the component's initial state. To do this, add a class constructor which assigns an initial state using this.state. The 'this.state' property can be rendered inside render() method. Example Cars.js import React from 'react'; class Cars extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford ", model: "Mustang ", EMERGING TRENDS AND TECHNOLOGIES color: "red ", year: 1964 }; } changeColor = () => { this.setState({color: "blue "}); } render() { return ( My {this.state.brand} It is a {this.state.color} {this.state.model} from {this.state.year}. Change color ); } } export default Cars; App.js import './App.css'; import Cars from './Cars'; function App() { return ( ); } export default App; Output: My Ford It is a red Mustang from 1964. Change color Change state EMERGING TRENDS AND TECHNOLOGIES My Ford It is a blue Mustang from 1964. Change color 2.4 EVENTS An event is an action that could be triggered as a result of the user action or system-generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events. React has its event handling system which is very similar to handling events on DOM elements. The react event handling system is known as Synthetic Events. The synthetic event is a cross-browser wrapper of the browser's native event. Handling events with react has some syntactic differences from handling events on DOM. These are: 1. React events are named as camelCase instead of lowercase. 2. With JSX, a function is passed as the event handler instead of a string. For example: Event declaration in plain HTML: 1. 2. Hello world 3. EMERGING TRENDS AND TECHNOLOGIES Event declaration in React: 1. 2. Hello world 3. 3. In react, we cannot return false to prevent the default behaviour. We must call preventDefault event explicitly to prevent the default behaviour. For example: Example Cars.js import React from 'react'; class Cars extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford ", model: "Mustang ", color: "red ", year: 1964 }; } changeColor = () => {this.setState({color: "blue "}); } render() { return ( My {this.state.brand} It is a {this.state.color} {this.state.model} from {this.state.year}. Change color ); } } export default Cars; App.js import './App.css'; import Cars from './Cars'; EMERGING TRENDS AND TECHNOLOGIES function App() { return ( ); } export default App; Output: My Ford It is a red Mustang from 1964. Change color Change state My Ford It is a blue Mustang from 1964. Change color EMERGING TRENDS AND TECHNOLOGIES UNIT-3 REACT FOR FRONT-END DEVELOPMENT 3.1 LISTS AND KEYS 3.1.1 Lists Lists are an important aspect of your app. Every application is bound to make use of lists in some form or the other. You could have a list of tasks like a calendar app, a list of pictures like Instagram, a list of items to shop in a shopping cart, and so on. The use cases are numerous. Lists within an application can be performance- heavy. Imagine an app with a huge list of videos or pictures and you keep getting thousands more, as you scroll. That could take a toll on the app’s performance. Because performance is an important aspect, when you use lists, you need to ensure they are designed for optimal performance. In JavaScript, the.map() method iterates through the parent array, calling a function on each element. Then it creates a new array containing the values that have been changed. It does not affect the parent array. Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus on a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. Creating and traversing a list: We can similarly create lists in Rea-+ct as we do in regular JavaScript i.e. by storing the list in an array. To traverse a list we will use the map() function. Step 1: Create a list of elements in React in the form of an array and store it in a variable. We will render this list as an unordered list element in the browser. Step 2: We will then traverse the list using the JavaScript map() function and update elements to be enclosed between elements. Step 3: Finally, we will wrap this new list within elements and render it to the DOM. App.js import React from 'react'; import ReactDOM from 'react-dom' function App() { const numbers = [1,2,3,4,5]; const updatedNums = numbers.map((number)=>{ return {number};}); EMERGING TRENDS AND TECHNOLOGIES ReactDOM.render( {updatedNums} , document.getElementById('root') ); } export default App; Output: The above code will render an unordered list as shown below Example NameList.js import React from 'react'; import ReactDOM from 'react-dom'; function NameList(props) { const listItems = myList.map((item) => {item} ); return ( {listItems} ); } const myList = ["apple", "orange", "strawberry", "blueberry", "avocado"]; ReactDOM.render( , document.getElementById('root') ); export default NameList; EMERGING TRENDS AND TECHNOLOGIES App.js import React from 'react' import NameList from './components/NameList'; function App() { return ( ); } export default App; Output: apple orange strawberry avocado 3.1.2 Keys What is a key in React? A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted. Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list. Assigning keys to the list. You can assign the array indexes as keys to the list items. The below example assigns array indexes as keys to the elements. The element's key is a specific property that must be included in the element, and it must be a string. Each list's key should be distinct, which means you shouldn't use values that are identical to the key. Each item within an array must have a unique key, but the key need not be globally unique. The same key can be used across various unrelated components and lists. To put it differently, keys should be unique among siblings rather than globally. The element's key serves as a form of identifier for React, allowing it to figure out which element was updated, added, or removed. EMERGING TRENDS AND TECHNOLOGIES It's a good idea to pick a value that serves as a unique identifier for each item in the array, which is usually the ID. Syntax: const numbers = [1, 2, 3, 4, 5]; const updatedNums = numbers.map((number, index) => {number} ); An issue with assigning index as keys: Assigning indexes as keys are highly discouraged because if the elements of the arrays get reordered in the future, then it will get confusing for the developer as the keys for the elements will also change. Difference between keys and props in React: Keys are not the same as props, only the method of assigning a “key” to a component is the same as that of props. Keys are internal to React and cannot be accessed from inside of the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the Component. Using Keys with Components: Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to and not to A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned a key. Example import React from 'react'; import ReactDOM from 'react-dom'; function ListComponent(props) { const listItems = myList.map((item) => {item.value} ); EMERGING TRENDS AND TECHNOLOGIES return ( {listItems} ); } const myList = [{id: 'a', value: "Lotus"}, {id: 'b', value: "Rose"}, {id: 'c', value: "Sunflower"}, {id: 'd', value: "Marigold"}, {id: 'e', value: "Lily"}]; ReactDOM.render( , document.getElementById('root') ); export default ListComponent Output: A. Lotus B. Rose C. Sunflower D. Marigold E. Lily 3.2 React Lifecycle Lifecycle of Components Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting. 3.2.1 Mounting Mounting means putting elements into the DOM. React has four built-in methods that get called, in this order, when mounting a component: constructor() getDerivedStateFromProps() render() componentDidMount() EMERGING TRENDS AND TECHNOLOGIES The render() method is required and will always be called, the others are optional and will be called if you define them. 3.2.1.1 constructor The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values. The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent's constructor method and allow the component to inherit methods from its parent (React.Component). 3.2.1.2 getDerivedStateFromProps The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props. It takes the state as an argument and returns an object with changes to the state. The example below starts with the favourite color being "red", but the getDerivedStateFromProps() method updates the favourite color based on the favcol attribute: ReactDOM.render(, document.getElementById('root')); Render: The render() method is required and is the method that outputs the HTML to the DOM. 3.2.1.3 componentDidMount The componentDidMount() method is called after the component is rendered. This is where you run statements that require that the component is already placed in the DOM. 3.2.2 Updating The next phase in the lifecycle is when a component is updated. A component is updated whenever there is a change in the component's state or props. React has five built-in methods that get called, in this order, when a component is updated: getDerivedStateFromProps() shouldComponentUpdate() getSnapshotBeforeUpdate() render() EMERGING TRENDS AND TECHNOLOGIES componentDidUpdate() The render() method is required and will always be called, the others are optional and will be called if you define them. 3.2.2.1 getDerivedStateFromProps Also, at updates, the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated. This is still the natural place to set the state object based on the initial props. Imagine an example has a button that changes the favourite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favourite color is still rendered as yellow. 3.2.2.2 shouldComponentUpdate In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not. The default value is true. 3.2.2.3 getSnapshotBeforeUpdate The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated. Any value returned by getSnapshotBeforeUpdate() method will be used as a parameter for componentDidUpdate() method. This function is always used along with the componentDidUpdate() method but vice-versa isn’t true. Syntax: getSnapshotBeforeUpdate(prevProps, prevState) Parameters: It accepts two parameters, they are prevProps and prevState which are just the props or state before the component in question is re-rendered. 3.2.2.4 render The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes. Imagine an example has a button that changes the favorite color to blue. EMERGING TRENDS AND TECHNOLOGIES 3.2.2.5 componentDidUpdate The componentDidUpdate method is called after the component is updated in the DOM. When the component is mounting it is rendered with the favourite color "red". When the component has been mounted, a timer changes the state, and the color becomes "yellow". This action triggers the update phase, and since this component has a componentDidUpdate method. 3.2.3 Unmounting The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it. React has only one built-in method that gets called when a component is unmounted: componentWillUnmount() The componentWillUnmount method is called when the component is about to be removed from the DOM. 3.3Hooks Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions that "hook into" React state and lifecycle features from function components. It does not work inside classes. Rules of Hooks Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. The hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are: 1. Only call Hooks at the top level Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a componentrenders. 2. Only call Hooks from React functions You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks. Pre-requisites for React Hooks Node version 6 or above EMERGING TRENDS AND TECHNOLOGIES NPM version 5.2 or above Create-react-app tool for running the React App 3.3.1 Hooks useState() Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state. Let us understand Hook state with the following example. App.js import React, { useState } from 'react'; function CountApp() { const [count, setCount] = useState(0); return ( You clicked {count} times setCount(count + 1)}> click me ); } export default CountApp; OUTPUT You clicked 3 times 3.3.2 Hooks useEffect() The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods. Side effects have common features that the most web applications need to perform, such as: Updating the DOM, Fetching and consuming data from a server API, Setting up a subscription, etc. EMERGING TRENDS AND TECHNOLOGIES App.js import React, { useState, useEffect } from 'react'; function CounterExample() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( You clicked {count} times setCount(count + 1)}> Click me ); } export default CounterExample; OUTPUT You clicked 2 times 3.4 Forms Just like in HTML, React uses forms to allow users to interact with the web page. Handling Forms Handling forms is about how you handle the data when it changes value or gets submitted. In HTML, form data is usually handled by the DOM. In React, form data is usually handled by the components. When the components handle the data, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute. We can use the useState() Hook to keep track of each input value and provide a "single source of truth" for the entire application. Example EMERGING TRENDS AND TECHNOLOGIES SimpleForm.js import React, { useState } from 'react'; const SimpleForm = () => { // State variables to store form input values const [textBoxValue, setTextBoxValue] = useState(''); const [textAreaValue, setTextAreaValue] = useState(''); const [radioValue, setRadioValue] = useState('option1'); const [checkBoxValue, setCheckBoxValue] = useState(false); const [checkBoxValue1, setCheckBoxValue1] = useState(false); const [checkBoxValue2, setCheckBoxValue2] = useState(false); // Function to handle form submission const handleSubmit = (e) => { e.preventDefault(); console.log('Form submitted!'); console.log('Text Box Value:', textBoxValue); console.log('Text Area Value:', textAreaValue); console.log('Radio Value:', radioValue); console.log('Check Box Value:', checkBoxValue); console.log('Check Box Value:', checkBoxValue1); console.log('Check Box Value:', checkBoxValue2); }; return ( {} Text Box: setTextBoxValue(e.target.value)}/> {} Text Area: setTextAreaValue(e.target.value)} /> EMERGING TRENDS AND TECHNOLOGIES {} setRadioValue('option1') }/> Option 1 setRadioValue('option2')} /> Option 2 setCheckBoxValue(!checkBoxValue) } /> Check me setCheckBoxValue1(!checkBoxValue1) } /> Check me1 setCheckBoxValue2(!checkBoxValue2) } EMERGING TRENDS AND TECHNOLOGIES /> Check me2 {} Submit );}; export default SimpleForm; Output: 3.5 Pulling Data from an API API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make their program easier and simpler. Also, an API facilitates the programmers with an efficient way to develop their software programs. Approach: we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from http://jsonplaceholder.typicode.com/users we have created the component in App.js and styling the component in App.css. From the API we have target “id”, “name”, “username”, “email” and fetch the data from API endpoints. Below is the stepwise implementation of how we fetch the data from an API in react. We will use the fetch function to get the data from the API. Step-by-step implementation to fetch data from an api in react: Step 1: Create React Project npm create-react-app MY-APP EMERGING TRENDS AND TECHNOLOGIES Step 2: Change your directory and enter your main folder charting as cd MY-APP Step 3: API endpoint https://jsonplaceholder.typicode.com/users Step 4: Write code in App.js to fetch data from API and we are using fetch function. Example: import React from "react"; import './App.css'; class App extends React.Component { // Constructor constructor(props) { super(props); this.state = { items: [], DataisLoaded: false }; } // ComponentDidMount is used to execute the code componentDidMount() { fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json()).then((json) => { this.setState({ items: json, DataisLoaded: true }); }) } render() { const { DataisLoaded, items } = this.state; if (!DataisLoaded) return Please wait some time.... ; return ( EMERGING TRENDS AND TECHNOLOGIES Fetch data from an api in react { items.map((item) => ( User_Name: { item.username }, Full_Name: { item.name }, User_Email: { item.email } ) ) } ); } } export default App; Output: Fetch data from an API in react User_Name: Bret, Full_Name: Leanne Graham, User_Email: [email protected] User_Name: Antonette, Full_Name: Ervin Howell, User_Email: [email protected] User_Name: Samantha, Full_Name: Clementine Bauch, User_Email: [email protected] User_Name: Karianne, Full_Name: Patricia Lebsack, User_Email: [email protected] User_Name: Kamren, Full_Name: Chelsey Dietrich, User_Email: [email protected] User_Name: Leopoldo_Corkery, Full_Name: Mrs. Dennis Schulist, User_Email: [email protected] User_Name: Elwyn.Skiles, Full_Name: Kurtis Weissnat, User_Email: [email protected] EMERGING TRENDS AND TECHNOLOGIES User_Name: Maxime_Nienow, Full_Name: Nicholas Runolfsdottir V, User_Email: [email protected] User_Name: Delphine, Full_Name: Glenna Reichert, User_Email: [email protected] User_Name: Moriah.Stanton, Full_Name: Clementina DuBuque, User_Email: [email protected] EMERGING TRENDS AND TECHNOLOGIES UNIT-4 Introduction to Node.js 4.1 Back-end Development Back-end development means working on server-side software, which focuses on everything you can’t see on a website. Back-end developers ensure the website performs correctly, focusing on databases, back-end logic, application programming interface (APIs), architecture, and servers. They use code that helps browsers communicate with databases, and store, understand, and delete data. Back-end developers must be familiar with many kinds of tools and frameworks, including languages such as Python, Java, and Ruby. They make sure the back end performs quickly and responsively to front-end user requests. Because performance is an important aspect, when you are using lists you need to make sure they are designed for optimal performance. Back-end developer tasks and responsibilities: Back-end developers are required to have technical expertise, analytical thinking, and excellent collaboration skills. As a back-end web developer, you should be able to work independently to design the web infrastructure. Build and maintain websites: A back-end developer’s main responsibility is to use various tools, frameworks, and languages to determine how best to develop intuitive, user-friendly prototypes and turn them into websites. This requires an understanding of cross-platform functionality and compatibility. Write high-quality code: To produce sustainable web applications, developers must write clean and easily maintainable code. Perform quality assurance (QA) testing: Create and oversee testing schedules to optimize user interface and experience, ensuring optimal display on various browsers and devices. Assess efficiency and speed: Once a website is up and running, and during updates and edits, developers need to assess its performance and scalability, adjusting code as necessary. Troubleshoot and debug: Be able to troubleshoot issues and resolve them, while communicating them to project managers, stakeholders, and QA teams. Train and support: Maintain workflows with client teams to ensure ongoing support, along with leading training and mentorship for junior developers. EMERGING TRENDS AND TECHNOLOGIES Which tools do back-end developers use? Web developers use a variety of tools to develop, test, and maintain web applications. Some common tools for back-end developers include: Programming languages: Python PHP JavaScript Ruby Java C# Frameworks: Laravel Django Spring Ruby on Rails Meteor Node.js Databases: MongoDB MySQL Oracle Back-end developer technical skills: As a back-end developer, there are certain technical skills you will need to learn to navigate developing the back-end of the web or mobile application. Programming languages: Any back-end developer needs to be well-versed in back-end programming languages such as Python, Java, and PHP. These make the website function when used alongside databases, frameworks, and servers. Python is one of the most popular programming languages because it is compatible EMERGING TRENDS AND TECHNOLOGIES with artificial intelligence (AI) and machine learning, and works well for writing clear and logical code. Basic knowledge of front-end languages HTML, CSS, and JavaScript is a bonus. Frameworks: Frameworks are the libraries of back-end programming languages that help to build the server configuration. They tend to be linked with programming languages, so if you are familiar with Python, you’ll also know Flask, Django, another Python-based framework, and so on. Databases and servers: You’ll need to understand how to stack and recover data from databases, as back- end programming controls access to this information, including storage and recovery. MongoDB and MySQL are popular database programs. The database stores and organizes the client’s data so that it can be easily arranged and recovered, just like you might use cloud storage for your photos. This database then runs on a server that provides data upon request. Application Program Interface (API): An API is a series of definitions and rules for developing application software. In addition to internet browser websites, companies often want a mobile app for iOS or Android. Knowledge of application-building languages like JavaScript will expand your job opportunities. Accessibility and security clearance: You should develop knowledge of network protocols and web security. Knowing how to secure databases and servers will be critical to your success as a back-end developer. 4.2 Client-side and Server-side JavaScript 4.2.1 Client-side VS Server-side JavaScript Client-side JavaScript: Client-side JavaScript refers to JavaScript code that is executed on the user's web browser. It's used to enhance the functionality and interactivity of web pages without requiring communication with the server. Common uses of client-side JavaScript include form validation, dynamic content updates, and user interface enhancements. Client-side JavaScript Example function greet() { var name = prompt("Enter your name:"); alert("Hello, " + name + "!"); EMERGING TRENDS AND TECHNOLOGIES } Click me In this example, when the "Click me" button is clicked, the client-side JavaScript code prompts the user for their name and displays a greeting using an alert box, all within the user's browser. 4.2.2 Server-side JavaScript Node.js is a powerful runtime environment for executing JavaScript code outside of a web browser. It brings the JavaScript language to the server side, enabling developers to build scalable, high-performance, and event- driven applications. Node.js allows developers to use JavaScript both on the client side and the server side, providing a unified language and ecosystem. This eliminates the need for context switching and enables code reuse between the front-end and back-end. This results in improved productivity and reduced development time. Node.js has a vast and active ecosystem of modules and libraries available through the Node Package Manager (npm). This rich ecosystem offers ready-to-use tools and packages for various functionalities, such as web frameworks, database connectors, authentication, and testing frameworks. Developers can leverage these modules to accelerate development and enhance application functionality. Given all that, Node.js is particularly well-suited for building: Web applications Scalable APIs Real-time applications requiring instant data updates and bidirectional communication like chat applications and multiplayer games Streaming applications like audio or video processing or real-time analytics Single-page applications Internet of Things deployments EMERGING TRENDS AND TECHNOLOGIES Example (Node.js): const http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from the server!'); }).listen(8080); 4.3 Introduction of Node.js Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project! Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. When Node.js performs an I/O operation, like reading from the network or accessing a database or the file system, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back. This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs. Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language. In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags. Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run real-time server applications. The definition given by its official documentation is as follows: Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js also provides a rich library of various JavaScript modules to simplify the development of web applications. EMERGING TRENDS AND TECHNOLOGIES Node.js = Runtime Environment + JavaScript Library. Following is a list of some important features of Node.js that make it the first choice of software architects: Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very fast in code execution. Single-threaded: Node.js follows a single-threaded model with event looping. Highly Scalable: Node.js is highly scalable because the event mechanism helps the server to respond in a non-blocking way. No buffering: Node.js cuts down the overall processing time while uploading audio and video files. Node.js applications never buffer any data. These applications simply output the data in chunks. Open source: Node.js has an open-source community that has produced many excellent modules to add additional capabilities to Node.js applications. 4.4 Node.js Modules What is a Module in Node.js? Consider modules to be the same as JavaScript libraries. A set of functions you want to include in your application. EMERGING TRENDS AND TECHNOLOGIES Built-in Modules Node.js has a set of built-in modules which you can use without any further installation. Include Modules: To include a module, use the require() function with the name of the module: var http = require('http'); Now your application has access to the HTTP module, and can create a server: http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!'); }).listen(8080); 4.4.1 Create Your Modules You can create your modules and easily include them in your applications. The following example creates a module that returns a date and time object: Example: Get your own Node.js Server Create a module that returns the current date and time: exports.myDateTime = function () { return Date(); }; Use the exports keyword to make properties and methods available outside the module file. Save the code above in a file called "myfirstmodule.js" Include Your Own Module Now you can include and use the module in any of your Node.js files. Example: Use the module "myfirstmodule" in a Node.js file: var http = require('http'); EMERGING TRENDS AND TECHNOLOGIES var dt = require('./myfirstmodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + dt.myDateTime()); res.end(); }).listen(8080); Notice that we use./ to locate the module, that means that the module is located in the same folder as the Node.js file. Save the code above in a file called "demo_module.js", and initiate the file: Initiate demo_module.js: C:\Users\Your Name>node demo_module.js 4.4.2 Node.js HTTP Module The Built-in HTTP Module Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method: var http = require('http'); Node.js as a Web Server The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. Use the createServer() method to create an HTTP server: Example: Get your own Node.js Server var http = require('http'); //create a server object: http.createServer(function (req, res) { EMERGING TRENDS AND TECHNOLOGIES res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8080); //the server object listens on port 8080 The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8080. Save the code above in a file called "demo_http.js", and initiate the file: Initiate demo_http.js: C:\Users\Your Name>node demo_http.js 4.5 Creating a web server An Example Node.js Application The most common example Hello World of Node.js is a web server: const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);}); To run this snippet, save it as a server.js file and run node server.js in your terminal. This code first includes the Node.js http module. Node.js has a fantastic standard library, including first-class support for networking. The createServer() method of http creates a new HTTP server and returns it. EMERGING TRENDS AND TECHNOLOGIES The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running. Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object). Those 2 objects are essential to handle the HTTP call. The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data. The second is used to return data to the caller. In this case with: res.statusCode = 200; we set the statusCode property to 200, to indicate a successful response. We set the Content-Type header: res.setHeader('Content-Type', 'text/plain'); and we close the response, adding the content as an argument to end(): res.end('Hello World\n'); 4.6 Node.js MySQL Node.js can be used in database applications. One of the most popular databases is MySQL. MySQL Database: To be able to experiment with the code examples, you should have MySQL installed on your computer. You can download a free MySQL database at https://www.mysql.com/downloads/. Install MySQL Driver Once you have MySQL up and running on your computer, you can access it by using Node.js. To access a MySQL database with Node.js, you need a MySQL driver. To download and install the "mysql" module, open the Command Terminal and execute the following: C:\Users\Your Name>npm install mysql EMERGING TRENDS AND TECHNOLOGIES Now you have downloaded and installed a mysql database driver. Node.js can use this module to manipulate the MySQL database: var mysql = require('mysql'); Create Connection Start by creating a connection to the database. Use the username and password from your MySQL database. demo_db_connection.js var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); }); Save the code above in a file called "demo_db_connection.js" and run the file: Run "demo_db_connection.js" C:\Users\Your Name>node demo_db_connection.js Which will give you this result: Output: Connected! Now you can start querying the database using SQL statements. Query a Database: Use SQL statements to read from a MySQL database. This is also called "to query" the database. The connection object created in the example above, has a method for querying the database: con.connect(function(err) { EMERGING TRENDS AND TECHNOLOGIES if (err) throw err; console.log("Connected!"); con.query(sql, function (err, result) { if (err) throw err; console.log("Result: " + result); }); }); The query method takes a sql statements as a parameter and returns the result. 4.6.1 Creating a Database: To create a database in MySQL, use the "CREATE DATABASE" statement: Example: Create a database named "mydb": var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); con.query("CREATE DATABASE mydb", function (err, result) { if (err) throw err; console.log("Database created"); }); }); EMERGING TRENDS AND TECHNOLOGIES Save the code above in a file called "demo_create_db.js" and run the file: Run "demo_create_db.js" C:\Users\Your Name>node demo_create_db.js Which will give you this result: Output: Connected! Database created 4.6.2 Creating a Table: Creating a Table To create a table in MySQL, use the "CREATE TABLE" statement. Make sure you define the name of the database when you create the connection: Example: Get your own Node.js Server Create a table named "customers": var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))"; con.query(sql, function (err, result) { if (err) throw err; console.log("Table created"); EMERGING TRENDS AND TECHNOLOGIES }); }); Save the code above in a file called "demo_create_table.js" and run the file: Run "demo_create_table.js" C:\Users\Your Name>node demo_create_table.js Which will give you this result: Output: Connected! Table created 4.6.3 Primary Key When creating a table, you should also create a column with a unique key for each record. This can be done by defining a column as "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique number for each record. Starting at 1, and increased by one for each record. Example: Create primary key when creating the table: var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))"; EMERGING TRENDS AND TECHNOLOGIES con.query(sql, function (err, result) { if (err) throw err; console.log("Table created"); }); }); Output: Connected! Table created 4.7 Node.js Events Node.js is perfect for event-driven applications. Events in Node.js: Every action on a computer is an event. Like when a connection is made or a file is opened. Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file: Example: Get your own Node.js Server var fs = require('fs'); var rs = fs.createReadStream('./demofile.txt'); rs.on('open', function () { console.log('The file is open'); }); Events Module Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own events. To include the built-in Events module use the require() method. In addition, all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object: var events = require('events'); var eventEmitter = new events.EventEmitter(); EMERGING TRENDS AND TECHNOLOGIES The EventEmitter Object You can assign event handlers to your own events with the EventEmitter object. In the example below we have created a function that will be executed when a "scream" event is fired. To fire an event, use the emit() method. Example var events = require('events'); var eventEmitter = new events.EventEmitter(); //Create an event handler: var myEventHandler = function () { console.log('I hear a scream!'); } //Assign the event handler to an event: eventEmitter.on('scream', myEventHandler); //Fire the 'scream' event: eventEmitter.emit('scream'); EMERGING TRENDS AND TECHNOLOGIES UNIT-5 Back-End Development using Node.Js 5.1 Introduction to web Frameworks A web framework (WF) or web application framework (WAF) is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications on the World Wide Web. Web frameworks aim to automate the overhead associated with common activities performed in web development. For example, many web frameworks provide libraries for database access, templating frameworks, and session management, and they often promote code reuse. Although they often target development of dynamic web sites, they are also applicable to static websites. Backend development using Node.js Types of Web frameworks: As web standards began to advance, the app logic shifted towards the client- ensuring smarter communication between the user and the web application. With logic on the client side, they (the client) can react swiftly to user input. This makes web apps more responsive, and easily navigable on any device. Thus, we have two functions of frameworks — a) the one to work on the server side, which helps to set up app logic on the server (backend) or b) to work on the client side (front end). Perform quality assurance (QA) testing: Create and oversee testing schedules to optimize user interface and experience, ensuring optimal display on various browsers and devices. EMERGING TRENDS AND TECHNOLOGIES The front-end frameworks mostly manage the external part of the website, i.e. what the user sees when they open the application. The back-end manages the internal part. Let’s take a deeper look, 1.Server-side Frameworks The rules and architecture of the server-side frameworks permit you to create simple pages, landings, and forms of different kinds. To create a web application with a well-developed interface you need a wider range of functionality. Server-side frameworks handle HTTP requests, database control and management, URL mapping, etc. These frameworks can improve security and form the output data- simplifying the development process. Some of the top server-side frameworks are – NET (C#) Django (Python) Ruby on Rails (Ruby) Express (JavaScript/Node.JS) Symfony (PHP) 2. Client-side Frameworks Client-side frameworks don’t take care of the business logic like the server-side ones. They function inside the browser. Therefore, you can enhance and implement new user interfaces. A number of animated features can be created with frontend and single page applications. Every client-side framework varies in functionality EMERGING TRENDS AND TECHNOLOGIES and use. Here are some client-side frameworks for comparison’s sake; all of whom use JavaScript as their programming language- Angular.JS Ember.JS Vue.JS React.JS 5.2 Express Framework 5.2.1 What is Express? Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express. Imagine an example, when the "Click me" button is clicked, the client-side JavaScript code prompts the user for their name and displays a greeting using an alert box, all within the user's browser. Express.js is built on top of Node.js, which means that it can take advantage of all the features and functions of Node.js, including its speed and scalability. Why Express.js is Used for? Here are some of the common use cases for Express.js: Single-page applications (SPAs): Express.js can be used to build SPAs, which are web applications that provide a seamless user experience by loading all the necessary resources on a single page. Mobile applications: Express.js can be used to build mobile applications that use web technologies like HTML, CSS, and JavaScript. RESTful APIs: Express.js is commonly used to build RESTful APIs that can be used by other applications to access and manipulate data. Server-side rendering: Express.js can be used for server-side rendering, which is the process of rendering web pages on the server before sending them to the client. EMERGING TRENDS AND TECHNOLOGIES Real-time applications: Express.js can be used to build real-time applications, which require constant communication between the client and server. Microservices: Express.js is also used for building microservices, which are small, independent services that can be combined to build a larger application. 5.2.2 Key Features of Express JS: Routing: Express.js provides a simple and flexible routing system that allows developers to map HTTP requests to specific functions. Middleware: Express.js provides middleware functions that can be used to perform various operations on incoming requests and outgoing responses. Middleware functions can be used to add functionality to your application, such as authentication, error handling, and more. Templates: Express.js provides a variety of template engines that can be used to render HTML pages. It supports popular template engines like EJS, Handlebars, and Pug. Error Handling: Express.js provides robust error handling features that help developers handle errors and exceptions in their applications. Security: Express.js provides built-in security features like Helmet, which helps protect against common security vulnerabilities like cross-site scripting (XSS) and cross-site request forgery (CSRF). Easy to Use: Express.js is easy to use and requires minimal configuration, making it ideal for developers who want to build web applications quickly. 5.2.3 Installing Express We can install it with npm. Make sure that you have Node.js and npm installed. Step - 1: Creating a directory for our project and making that our working directory. EMERGING TRENDS AND TECHNOLOGIES $ mkdir test $ cd test Step - 2: Using the npm init command to create a package.json file for our project. $ npm init This command describes all the dependencies of our project. The file will be updated when adding further dependencies to the project. Step - 3: Now in your test(name of your folder) folder type the following command: $ npm install express –save 5.3 Create Application using Express Project Structure: It will look like the following. Example: Write the following code in app.js. var express = require("express"); var app = express(); app.get("/", function (req, res) { res.send("Welcome to My Project"); }); app.listen(3000); Step to run the application: Start the app by typing following command. node app.js Output: EMERGING TRENDS AND TECHNOLOGIES How the App Works? The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app. app.get(route, callback) This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request. res.send() This function takes an object as input and it sends this to the requesting client. Here we are sending the string "Hello World!". app.listen(port) 5.4 Routing, Middleware, Templating 5.4.1 Routing: Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. The following function is used to define routes in an Express application − app.method(path, handler) EMERGING TRENDS AND TECHNOLOGIES This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type. Put is the route at which the request will run. Handler is a callback function that executes when a matching request type is found on the relevant route. For example, var express = require('express'); var app = express(); app.get('/hello', function(req, res){ res.send("Hello World!"); }); app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello", our Express app executes the callback function attached to this route and sends "Hello World!" as the response. We can also have multiple different methods at the same route. For example, var express = require('express'); var app = express(); app.get('/hello', function(req, res){ res.send("Hello World!"); }); EMERGING TRENDS AND TECHNOLOGIES app.post('/hello', function(req, res){ res.send("You just called the post method at '/hello'!\n"); }); app.listen(3000); To test this request, open up your terminal and use URL to execute the following request − curl -X POST http://localhost:3000/hello A special method, all, is provided by Express to handle all types of http methods at a particular route using the same function. To use this method, try the following. app.all('/test', function(req, res){ res.send("HTTP method doesn't have any effect on this route!"); }); This method is generally used for defining middleware, which we'll discuss in the middleware. Example: Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we will use Express.Router. Create a new file called things.js and type the following in it. var express = require('express'); var router = express.Router(); router.get('/', function(req, res){ res.send('GET route on things.'); }); router.post('/', function(req, res){ res.send('POST route on things.'); }); //export this router to use in our index.js module.exports = router; Now to use this router in our index.js, type in the following before the app.listen function call. var express = require('Express'); var app = express(); var things = require('./things.js'); EMERGING TRENDS AND TECHNOLOGIES //both index.js and things.js should be in same directory app.use('/things', things); app.listen(3000); The app.use function call on route '/things' attaches the things router with this route. Now whatever requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you will see the following output. 5.4.2 Middleware: You can create your own modules, and easily include them in your applications. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware function in the stack. EMERGING TRENDS AND TECHNOLOGIES The following example creates a module that returns a date and time object: Example: Create a module that returns the current date and time: exports.myDateTime = function () { return Date(); }; Use the exports keyword to make properties and methods available outside the module file. Save the code above in a file called "myfirstmodule.js" Include Your Own Module Now you can include and use the module in any of your Node.js files. Example: Use the module "myfirstmodule" in a Node.js file: var http = require('http'); var dt = require('./myfirstmodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + dt.myDateTime()); res.end(); }).listen(8080); Notice that we use./ to locate the module, that means that the module is located in the same folder as the Node.js file. Save the code above in a file called "demo_module.js", and initiate the file: Initiate demo_module.js: C:\Users\Your Name>node demo_module.js 5.4.3 Templating: To use Pug with Express, we need to install it, npm install --save pug Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file. EMERGING TRENDS AND TECHNOLOGIES app.set('view engine', 'pug'); app.set('views','./views'); Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it. doctype html html head title = "Hello Pug" body p.greetings#people Hello World! To run this page, add the following route to your app − app.get('/first_template', function(req, res){ res.render('first_view'); }); You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to − Hello Pug Hello World! Pug is capable of doing much more than simplifying HTML markup. Important Features of Pug: Let us now explore a few important features of Pug. EMERGING TRENDS AND TECHNOLOGIES Simple Tags Tags are nested according to their indentation. Imagine an example, was indented within the tag, so it was inside it. But the tag was on the same indentation, so it was a sibling of the tag. We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us. To put text inside of a tag, we have 3 methods − Space seperated h1 Welcome to Pug Piped text div | To insert multiline text, | You can use the pipe operator. Block of text div. But that gets tedious if you have a lot of text. You can use "." at the end of tag to denote block of text. To put tags inside this block, simply enter tag in a new line and indent it accordingly. Comments Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(). For example, //This is a Pug comment This comment gets converted to the following. EMERGING TRENDS AND TECHNOLOGIES Attributes To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag. div.container.column.main#division(width = "100", height = "100") This line of code, gets converted to the following. − Pug.js rendering from string We start with a very simple example that renders from a string. Example: simple.js import { render } from 'pug'; const template = 'p #{name} is a #{occupation}'; const data = { 'name': 'John Doe', 'occupation': 'gardener' }; const output = render(template, data); console.log(output); The example shows output from a string template. import { render } from 'pug'; We load the render function from pug module. const template = 'p #{name} is a #{occupation}'; This is our simple string template. The first value is the tag to be rendered. In addition, we add two variables: nameand occupation. To output the variables we use the #{} syntax. const data = { 'name': 'John doe', 'occupation': 'gardener' }; This is the data that we pass to the template engine. const output = render(template, data); The render function takes a template string and the context data. It compiles both into the final string output. OUTPUT: $ node app.js John Doe is a gardener EMERGING TRENDS AND TECHNOLOGIES EXAMPLE: Pug.js compileFile The compileFile function compiles a Pug template from a file to a function which can be rendered multiple times with different locals. template.pug p Hello #{name}! This is the template file; it has a.pug extension. app.js import { compileFile } from 'pug'; const cfn = compileFile('template.pug'); const res = cfn({'name': 'John Doe'}); console.log(res); const res2 = cfn({'name': 'Roger Roe'}); console.log(res2); We compile the template to a function and call the function with two different local data. OUTPUT: $ node app.js Hello John Doe! Hello Roger Roe! EXMAPLE: Pug.js renderFile The renderFile function compiles a Pug template from a file and render it with locals to HTML string. template.pug doctype html html body ul li Name: #{name} li Occupation: #{occupation} EMERGING TRENDS AND TECHNOLOGIES In the tempalte, we have a small HTML document with an unordered list. We have two variables. app.js import { renderFile } from 'pug'; const options = { 'pretty': true } const locals = { 'name': 'John doe', 'occupation': 'gardener', }; const res = renderFile('template.pug', Object.assign(locals, options)); console.log(res); We merge the locals and the options with Object.assign; const options = { 'pretty': true } In the options map, we set the pretty printing. (Note that this option is deprecated.) OUTPUT: $ node app.js Name: John doe Occupation: gardener 5.5 HTTP Method and RESTful APIs 5.5.1 HTTP Method: The HTTP method is supplied in the request and specifies the operation that the client has requested. GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. POST EMERGING TRENDS AND TECHNOLOGIES The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI. PUT The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one. DELETE The DELETE method requests that the server delete the specified resource. 5.5.2 RESTful APIs: RESTful URIs and methods provide us with almost all information we need to process a request. The table given below summarizes how the various verbs should be used and how URIs should be named. We will be creating a movies API towards the end; let us now discuss how it will be structured. Method URI Details Function GET /movies Safe, cachable Gets the list of all movies and their details GET /movies/1234 Safe, cachable Gets the details of Movie id 1234 Creates a new movie with the details POST /movies N/A provided. Response contains the URI for this newly created resource. Let us now create this API in Express. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has other benefits. Replace your index.js file with the movies.js file as in the following program. index.js: var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.use(cookieParser()); app.use(bodyParser.json()); EMERGING TRENDS AND TECHNOLOGIES app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); //Require the Router we defined in movies.js var movies = require('./movies.js'); //Use the Router on the sub route /movies app.use('/movies', movies); app.listen(3000); Now that we have our application set up, let us concentrate on creating the API. Start by setting up the movies.js file. We are not using a database to store the movies but are storing them in memory; so every time the server restarts, the movies added by us will vanish. This can easily be mimicked using a database or a file (using node module). Once you import Express then, create a Router and export it using module.exports – var express = require('express'); var router = express.Router(); var movies = [ {id: 101, name: "Fight Club", year: 1999, rating: 8.1}, {id: 102, name: "Inception", year: 2010, rating: 8.7}, {id: 103, name: "The Dark Knight", year: 2008, rating: 9}, {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9} ]; //Routes will go here module.exports = router; GET routes: Let us define the GET route for getting all the movies − router.get('/', function(req, res){ res.json(movies); }); To test out if this is working fine, run your app, then open your terminal and enter − curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies EMERGING TRENDS AND TECHNOLOGIES The following response will be displayed − [{"id":101,"name":"Fight Club","year":1999,"rating":8.1}, {"id":102,"name":"Inception","year":2010,"rating":8.7}, {"id":103,"name":"The Dark Knight","year":2008,"rating":9}, {"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}] We have a route to get all the movies. Let us now create a route to get a specific movie by its id. router.get('/:id([0-9]{3,})', function(req, res){ var currMovie = movies.filter(function(movie){ if(movie.id == req.params.id){ return true; } }); if(currMovie.length == 1){ res.json(currMovie) } else { res.status(404);//Set status to 404 as movie was not found res.json({message: "Not Found"}); } }); This will get us the movies according to the id that we provided. To check the output, use the following command in your terminal − curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies/101 You'll get the following response − {"id":101,"name":"Fight Club","year":1999,"rating":8.1} If you visit an invalid route, it will produce a cannot GET error while if you visit a valid route with an id that doesn’t exist, it will produce a 404 error. POST routes: Use the following route to handle the POST data − router.post('/', function(req, res){ EMERGING TRENDS AND TECHNOLOGIES //Check if all fields are provided and are valid: if(!req.body.name || !req.body.year.toString().match(/^[0-9]{4}$/g) || !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){ res.status(400); res.json({message: "Bad Request"}); } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: req.body.name, year: req.body.year, rating: req.body.rating }); res.json({message: "New movie created.", location: "/movies/" + newId}); } }); This will create a new movie and store it in the movies variable. To check this route, enter the following code in your terminal − curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" http://localhost:3000/movies The following response will be displayed − {"message": "New movie created." ,"location":"/movies/105"} To test if this was added to the movies object, Run the get request for /movies/105 again. The following response will be displayed − {"id":105,"name":"Toy story","year":"1995","rating":"8.5"}