Completed an intensive Full-stack Web Development course, gaining proficiency in HTML/CSS/JavaScript/jQuery, NodeJS/ExpressJS, MongoDB, and ReactJS, and successfully built 16 web development projects
-
Course details
What you'll learn :
- Build 16 web development projects for your portfolio, ready to apply for junior developer jobs.
- After the course you will be able to build ANY website you want.
- Work as a freelance web developer.
- Master backend development with Node
- Learn the latest technologies, including Javascript, React, Node and even Web3 development.
- Build fully-fledged websites and web apps for your startup or business.
- Master frontend development with React
- Learn professional developer best practices.
- 65 hours on-demand video
- 49 downloadable resources
- 86 articles
- 14 coding exercise projects
Course includes :
- Front-End Web Development
- HTML 5
- CSS 3
- Bootstrap 4
- Javascript ES6
- DOM Manipulation
- jQuery
- Bash Command Line
- Git, GitHub and Version Control
- Backend Web Development
- Node.js
- NPM
- Express.js
- EJS
- REST
- APIs
- Databases
- SQL
- MongoDB
- Mongoose
- Authentication
- Firebase
- React.js
- React Hooks
- Web Design
- Deployment with GitHub Pages, Heroku and MongoDB Atlas
- Web3 Development on the Internet Computer
- Blockchain technology
- Token contract development
- NFT minting, buying and selling logic
Front-End Web Development
- Internet is a long piece of wire, And that wire connects different computers to each other. It allows computers to transfer data through this giant wire
- A server is a computer that provides files and data to other computers, it allows access 24/7.
- A client is a computer that any user is used to access the internet.
- When the browser request a website, the request is sent to ISP (Internet server provider: The company we pay for internet service) then it searches at DNS that contains the web site's IP addresses. Once the DNS finds the IP address it sends it back to the browser vis ISP. Then the browser sends a direct request through ISP and this message will be delivered via Internet Backbone to the server that is located at that IP address. On that server, all files are needed to view the website home page. The server sends these files back to the client through the internet backbone and the client gets to see the website in the browser. All of that happens in milliseconds.
- To access the web page we need a browser (allows to look up at IP address and receives data from the server).
- Data from the server contains HTML, CSS, and js files.
- Need Browser (chrome recommended)
- Text Edittor(Atom, vs code)
Introduction to HTML
- HTML : Hyper Text Markup Language.
- A markup language is a computer language that uses tags to define elements within a document.
- html is the foundation of all websites.
- Tag consist of: open tag
<typeOfTag> and closing tag </typeOfTag>
. - Ex: Heading tag h1, h2, ….,h6 . It gets smaller when the number goes up.
- called self-closing tag.
- Ex: Spacing breack tag
br
.
- < startTag > Content </ EndTag >
- Horizontal line tag hr accepts attribute size, noshade,..
- Attributes specify modification to the default element.
- Center content using tag
<center>content</center>
. - Comments are not interpreted by the compiler
<!-- Comment -- >
.
- It Is a code template that could be reused.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"> //tell the browser that all text in page are encoded using utf-8 encoding system wich is the standered encoding.
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<script src="js/scripts.js"></script>
</body>
</html>
meta
tag utf-8 tell the browser that all texts on the page are encoded using utf-8 encoding system which is the standard encoding.- Unicode “utf-8” has all characters and emojis.
- There is a different types of
meta
tags for diffrent purposes.
- The code goes inside the body tag.
- Paragraph tag
p
. - emphasis Tag
em
tells the browser that the words between it is emphasis, not just about style. - italic tag
i
style element. - Strong tag
strong
tells the browser that the words between it is Strong Importance Element. bold
tag bold styles bold.
- There are two types of lists.
- Ordered lists
ol
and unordered listsul
. - Each type has children
li
for each item of the list. ol
list has attributes: start and type to control the list items.
- Self-closing tag that must be with
src
attribute to the image url. alt
attribute helps google searching.
- HTML : HyperText Markup Language.
- HyperText is some parts of data that connect with hyper links, so when you click on it takes to another part.
- Anchor tags is closing tag
<a> Link text </a>
. href
attribute is the link destination.
Intermediate HTML
- Tables main tag is
table
, and everything between is the actual content. - To make row use tag
tr
. - To make cell inside the row use
td
.
<table>
<thead>
<tr>
<th colspan="2">The table header</th>
</tr>
</thead>
<tbody>
<tr>
<td>The table body</td>
<td>with two columns</td>
</tr>
</tbody>
</table>
- main form tag is
form
to define what should go into our form. label
tag to some text related to theinput
element.- To use different inputs simply change the
type
of theinput
to what is needed. textarea
tag to write message.- To submit
form
button useinput
withtype=”submit”
.
- use GitHub to publish free.
- Make a new repository.
- Initialize with a readme file.
- Upload project files
- Give the version a name and commit.
- Go to settings -> GitHub pages -> source
- Change source from none to the main branch.
- Now the website can be accessed by the internet.
Introduction to CSS
- CSS: cascading style sheet.
- Styling html.
- Going into the tag and change style
attribute = "property:value;"
.
- Add
style
tag inside thehead
tag. - Select element inside
style
tag. - Make styles ->
selector {Property : value}
.
<head>
<style>
body {
background-color: linen;
}
</style>
</head>
- No website is completely unstyled. That means that there is default styles being applied by the browser.
hr
tag has border style default values.- One of the most important role in CSS is to realize that everything in HTML is a box, and the style of these boxes can be affected by changing CSS styles.
height
property isn’t uniqe.background-color
,height
,width
properties.- Change default values to achieve the style needed.
- Add styles in external file.css.
link
this file to html page athead
tag.- Anything in html is affected with this external css.
- This the best way to apply css.
- Errors in the console for link href for an external file.
- Inline styles override the external and internal styles.
- Internal styles override the external styles.
selector {
propery: value;
}
// who { what: how; }
- Using tag name.
tagName {
propery: value;
}
- Using class attribute to specify styles for individual
html
element .
.class{
propery: value;
}
- Using
id
attribute. - We can only have one instance of one particular tag
id
inside a single page. id
can only use in one place.id
use to identify one element.
#id {
propery: value;
}
class
can be used for a group of related items.id
used to apply specific styles to a single element.- Any HTML element can have more than one class.
- A pseudo-class is used to define a special state of an element
selector:pseudo-class {
property: value;
}
Intermediate CSS
- It started as an image that appears when the user adds the site to the favorites list, and now it is an image that appears next to the title of the site page.
- Favicon.com to create the favicon.
- Import it using link tag with
rel=”icon”
inside the head tag.
- Div is a special HTML element that allows us to divide content into separate containers or boxes.
- It has a height if specify it using style or if it has a content.
- Width and height of the element are pushing any other element.
- Border-width make outside border and affect the size of that element.
- Padding makes spaces inside the element and affects the size of that element.
- Margin makes space around elements and pushing them away.
- Inspect in chrome developer tools show box model to customize element.
- block elements take the whole width of the document.
- it doesn't allow another element to set at the same line.
- inline elements take the width of the content only.
- it doesn't allow to change the element width.
- there is an inline-block value, that allows to change width and set elements at the same line.
img
element treats as an inline-block.- none value removes the element from the web page as it didn't exist.
- visibility: hidden -> disappear the element but still exist at the dom.
- there are default roles despite any CSS styles.
- first role: content is everything -> content is the first thing that determined how large things get displayed and what the height and width will be.
- second role: the order of elements that comes from HTML code -> how we write code into HTML file is how it be displayed.
- third role: children sit on parents -> that means that child goes on top of the parent(static position).
- To make changes to the order of elements use position property.
- static position is the default position of all HTML elements.
- Relative position it allows us to position element that we select relative to how it would be positioned had it been static.
- coordinates: top, bottom, left, right -> determines we want to move element.
- when move element with relative position it doesn't affect any other thing in the screen.
- it as if the old position is kept and everything else flows around it.
- top with relative make margin top from the static position.
- with absolute positioning we positioning the element relative to it's parent .
- it is about adding a margin relative to it's parent element.
- fixed position -> fixs element in it's position relative to the body of the website and it doesn't moves despite scrolling. .
- text-align: center -> works with inline and block displayed elements that doesn't have width.
- margin: auto -> works with elements that have width.
- font-family: sans, sans-serif -> main fonts.
- google fonts to specific font. Link the fonts to html and use it with font-family property.
- font-size: px -> static size.
- % to make size dynamic.
- 100% == 16px
- 1 em == 16px
- with % and em font size get inhereted from parent and added to the child.
- The difference between px and % or em that px doesn't inherte from parent.
- rem = ignore the parent size(root element), that mean parent size won't affect on the child.
- to change font color use color propery.
- font-weight.
- line-height: number -> number without measuring unit.
- float element left or right.
- float make other elements at the same row.
-
other elements use clear property to clear float Effect.
- clear value is anti the float value.
Introduction to Bootstrap
- Bootstrap is a front-end library, It's a free open source.
- front-end is whatever the user sees.
- backend determine how everything is going to work.
- Responsive means that it response to the view port.
-
copy bootstap cdn -> the simplest way.
-
cdn -> stands for content delivery network.
-
the concept is instead of hosting website in single location, you have hole bunch of points where that website can be accessed, it looks for the shortest location that website can be delivered.
-
when browser reachs cdn link it looks for the shortest root to download bootstrap files if the user doesn't download it.
-
when it dowloaded broweser cashes files and doesn't need to redownload it.
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>Hello, world!</h1> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <!-- Option 2: jQuery, Popper.js, and Bootstrap JS <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script> --> </body> </html>
- Wireframing -> settle all design before coding it(using sketch).
- markup -> high fidelity representation of design. what you see is what you end up getting(using photoshop).
- prototyppe -> animated version of website.
- CSS code is executed from bottom to top so the order of your code matters
- Unlike CSS and JavaScript, HTML code is executed from top to bottom so the order of your code matters.
- all content goes inside container.
- container-fluid -> takes 100% width of the screen.
- Buttons Documentation.
- link fontAwesome library to our website.
- fontAwesome.
Intermediate Bootstrap
- slideshow.
- set carousel options by adding data-option="value".
- Documentation.
- aria-hidden="true" -> to be hidden from screen reader.
- class="sr-only" -> to screen reader only.
- Each element has x, y and z aixs.
- the default z-index for all elements is 0.
- -1 -> shows the element behind everything.
- z-index only work when element has position fixed, absolute and relative.
- static position doesn't make z-index work.
- Make website responsive by media query.
- @media < type > ( feature )
- there is many types of media like print, speach, screen.
- Code Refactoring:
- Readablity -> easy to understand not just for urself but to your future self, and for others.
- Modularity -> how easy to use bets of code.
- Efficiency -> how fast does your code run.
- length.
- selector1, selector2 { sharedProperty }
- Hierarchical Selectors -> selector1(parent) selector2(child){propertyAppiedToChild}
- Combined Selectors -> selector1.selctor2{ProprtyToTheSameElement}
- the last css role has priorety over everything above it.
- class is more specific than html selector, So it has high priorty.
- id has the highest priorty than class and html.
Web Design School - Create a Website that People Love
- Users take milliseconds to judge the product through it's design.
- Design is the cheapest way to make product look expensive.
- principles of design:
- color theory -> Every main color have a mood.
- Red -> love, energy, intensity.
- Yellow -> Joy, intellect, attention
- Green -> freshness, safty, growth.
- Blue -> stability, trust, serenity.
- Purble -> Royality, wealth, feminity.
- what msg I wanna give to User?
- colorbullet.
- like colors, fonts have different moods.
- serif family -> traditional, stable, respectable.
- use only 2 fonts to one design.
-
hierarchy:
- eyes look at big items first.
- color can make eyes look at the item directly.
-
layout :
- different size, image, shape .
- lenght of each line of text doesn't be too short or too long.
-
Alignment:
- Position items on website relative to each other.
- reduce the number of aligments
-
white space (space around elements):
- By adding more space around the element it makes design more minimilize and more elevated.
-
Audience:
- Think about the audience and what important for them.
- flexibility important for design.
-
simplicity.
-
Consistency:
- but also keep the functionality.
- make it simple to use, not make user learn how to use.
-
Reading Patterns
-
All platform design
- Responsive is very important.
- Not take much scroll to know what is going on in the website.
- Not make much warning messages.
-
Don't use Your Powers For Evil
- Don't make user make actions that he don't neccessarly do this. Ex. make btn that buy for something colored to buy more than the main buying btn.
- Help user to do what they want to do.
Introduction to Javascript
- It also known EcmaScript.
- java vs javaScript is like car vs carprt.
-
js id interpreted programming language, java is compiled programming language.
- It started as front-end language to make animation.
- Google chrome provide developer tool console to write line by line js code.
- using source tap inside console tap to write multiple lines of js code.
- source -> snippts -> new snippt (file.js);
alert('Message to be alerted.');
//keyword("")end
- String -> everything inside "" or ''.
- Numbers.
- Boolean -> true or false.
- typeof(variable) -> tells the type of the variable.
- prompt('msg') -> allows user to write input.
- var name = value -> to define variable.
- naming variables using camelCase.
- always give meaning names to variables.
- variables name can't be a keyword.
- variables name can't begin with numbers but it can contain number.
- variables name can't contain Spaces.
- numbers, characters, _ , $ are the only simpoles that valid.
- concat two or more strings using + -> Str1 + str2 = srt1str2.
- str.length -> returns the numbers of str characters.
- programmers always count from 0.
- slice(startindex, endIndex) -> Starting from StartIndex untill but not incloding endIndex and returns that new str.
var tweet = prompt("Msg limited to 140 char.")
var sliceTweet = tweet.slice(0, 140)
alert("You tweeted: " + sliceTweet)
- str.toUpperCase() -> all characters to upperCase.
- str.toLowerCase() -> all characters to lowerCase.
var name = prompt("Enter Name")
var fLetter = name.slice(0, 1);
var restOfLetters = name.slice(1, name.length);
alert("Your name is: " + fLetter.toUpperCase() + restOfLetters.toLowerCase())
- Modulo -> gives the remainer of the division (num % num).
- Modulo checkes if a number is fully divisible by another number.
- var x = 1 ; x = x + 1; -> Equals x++ ->Equals x += x
- var x = xNum; var y = yNum -> x += y // adding y to x
- += , -=, *=, /= all works the same.
- Functions -> is package reapeted code into {} and giving it a name.
- all that blocked code will be exicuted when you call that function.
- creating a function -> function funcName(){//package of code}
- calling function -> funcName();.
- functions take inputs called parameters.
- It's variable that can be used in this function.
- Math.floor(number) -> round down Number.
function lifeInWeeks(age) {
//Write your code here.
var leftedYears = 90 - age;
var days = leftedYears * 365;
var weeks = leftedYears * 52;
var months = leftedYears * 12;
console.log("You have " + days + " days, " + weeks + " weeks, and " + months + " months left.")
}
lifeInWeeks(25)
- In order to have output from function we have to use return keyword.
Intermediate Javascript
- Math.random() -> generates random number between 0 and 0.999999999999 it never reachs 1.
- Documentation.
- Math.random() * num -> range of numbers is from 0 to less than (not including) num.
- Pseudorandom number generators](https://www.youtube.com/watch?v=GtOt7EBNEwQ).
- Math.floor(Math.random() * n) +1 -> generates Number between 1 to n.
- control flow -> controling the flow of code depends on condition.
- Comparators -> compare two different values.
- ===, ==, <, >, <=, >=, !==, !=.
- The important difference between === and == is even though === check for equality also checking the type of data type.
- AND &&, OR ||, NOT !.
function bmiCalculator (weight, height) {
var interpretation = weight / (height *2);
if (interpretation < 18.5)
{
return "Your BMI is " + interpretation + ", so you are underweight.";
}
else if (interpretation >= 18.5 && interpretation <= 24.9)
{
return "Your BMI is " + interpretation + ", so you have a normal weight.";
}
else {
return "Your BMI is " + interpretation + ", so you are overweight.";
}
return interpretation;
}
function isLeap(year) {
if (year % 4 === 0 ) {
if(year % 100 === 0){
if(year % 400 === 0){
return "Leap year."
}else{
return "Not leap year."
}
}else{
return "Leap year."
}
} else {
return "Not leap year."
}
}
- Arrays -> is a collection of related items that can be stored together into the same variable.
- var arr = [item1, item2, item3, ....].
- arr[0] -> returns the fisrt index.
- arr.length -> the number of array items.
- arr.includes(item) -> check if this item is exist, it returns true or false.
- arr.push(value) -> Adding new item at the end of the array.
- arr.pop() -> Remove the last item of the array.
- fizzBuzz Game :
var result = [];
var count = 1;
function fizzBazz(){
while(count <= 100 ){ //while loop
if (count % 3 === 0 && count % 5 ===0){
result.push("fizzBuzz")
}else if(count % 3 === 0){
result.push("fizz")
}else if (count % 5 === 0){
result.push("buzz")
}else{
result.push(count)
}
count++;
}
console.log(result);
}
- The order of if statements is matter.
function whosPaying(names) {
var arrayLength = names.length;
var randomIndex = Math.floor(Math.random() * arrayLength);
return names[randomIndex] + " is going to buy lunch today!";
}
- To make sequance of data.
- while(end){//Sequance something ; change}
- satete -> if something is true.
- The bad thing about while loop is that it will run the program as long the condition is true, So it might be infinte loop.
//Bottels Challenge solution
var numberOfBottles = 99
while (numberOfBottles >= 0) {
var bottleWord = "bottle";
if (numberOfBottles === 1) {
bottleWord = "bottles";
}
console.log(numberOfBottles + " " + bottleWord + " of beer on the wall");
console.log(numberOfBottles + " " + bottleWord + " of beer,");
console.log("Take one down, pass it around,");
numberOfBottles--;
console.log(numberOfBottles + " " + bottleWord + " of beer on the wall.");
}
- for(start; end; change){//Sequance something}.
- iterate -> run a piece of code many times.
- Fibonacci Callenge
function fibonacciGenerator (n) {
var output = [];
if(n === 1){
output = [0];
}else if (n=== 2){
output = [0, 1];
}else{
output = [0, 1];
for(var i = 2; i< n; i++){
output.push(output[output.length -2] + output[output.length - 1]);
}
}
return output;
}
The Document Object
- Inline js -> By adding attributes to html elements, EX. onload="jsCode".(Not a good practice).
- Enternal -> By adding script type="text/javascript" tag to page and write js code inside it.
- External file -> script tag with src to the external js file.
- js scripts tag goes at the bottom of code unlike css links.
- DOM -> Document Object Model.
- it turns the document into a tree of objects that can be related to each others.
- HTML tree Generator Extention.
- Each child enhirets a document object.
- firstElementChild.
- lastElementChild.
- Objects inside the DOM has properties(describes thomething about object) and methods(the things that object can do).
- Metod -> is associated to an object.
- style property -> to change the css styles.
- Css properites in js.
- html file -> to strucure
- css files -> to style
- js file -> to behaviour
- Adding classes using js and style that classes using css.
- element.classList -> returns the list of classes.
- element.classList.add("className") -> add class to element.
- element.innerHTML -> all child html.
- element.textContent -> the child text only without html tags.
Boss Level Challenge 1 - The Dicee Game
- Dicee Game project.Advanced Javascript and DOM Manipulation
- Drum kit project.
- Higher Order Functions -> are functions that takes other functions as inputs or returns function as an output.
- Constructor: A constructor is a function that initializes an object.
- Constructor functions -> the name has to be capitalized.
// Create constructor
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
//create objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
- switch takes code into different track depending on differnt value.
- Method is a function that associated with an object.
- calling methods and ptoperty -> with dot notation.
var crash = new Audio("./sounds/crash.mp3") //Create object from Audio constructor
crash.play() // Use play function from the Audio constructor
- using eventListner keydown.
- Callback function -> is a function that gets passed in as an input.
- It has to wait something to happens.
- It triggers the actual event that happens.
- Adding class to clicked btn and setTimeout to remove the class
jQuery
14.1. What is jQuery?
- jQuery is javascript library that someone wrote it to simplify js code and make it easy to use.
14.2. How to Incorporate jQuery into websites
- Download jquery file or use cdn link.
- include scripts at the end of website or add the code inside ready function to avoid loading js file before loading jquery file.
$( document ).ready(function() {
// Handler for .ready() called.
});
14.3. How Minification Works to Reduce File Size
- Minify file removes spaces, comments and new lines to Reduce File Size.
- Minifier website.
14.4. Selecting Elements with jQuery
- Using $('selector').
14.5. Manipulating Styles with jQuery
- $('Selector').css('cssProperty', 'value') -> To set the value.
- $('Selector').css('cssProperty', 'value') -> To get the value.
- $('Selector').addClass('classname1 className2'), $('Selector').removeClass('classname1 className2').
- $('Selector').hasClass('className') -> return true or false.
14.6. Manipulating Text with jQuery
- $('Selector').text('Text to be added').
- $('Selector').html('< htmlTag />').
14.7. Manipulating Attributes with jQuery
- $('Selector').attr('attName', 'value') -> To set the attr value.
- $('Selector').attr('attName', 'value') -> To get the attr value.
- class is also attr.
14.8. Adding Event Listeners with jQuery
- $('Selector').eventName(callbackFunction) -> It triggers all element that matches Selector without having to make for loop.
- $('Selector').on("eventName", callbackFunction).
14.9. Adding and Removing Elements with jQuery
- element.before(element) -> creates element before the target element itself(before the opening tag of the selected element).
- element.prepend(element) -> creates element before the content of target element.
- element.after(element) -> creates element after the target element itself(after the opening tag of the selected element).
- element.apend(element) -> creates element after the content of target element.
- element.remove() -> Removes all selected elements.
14.10. Website Animations with jQuery
- element.hide(), element.show(), element.toggle().
- element.fadeOut(), element.fadeIn(), element.fadeToggle().
- element.slideUp(), element.slideDown(), element.slideToggle().
- element.animate({poperty: value}) -> we can only add css roles that a numeric value.
Boss Level Challenge 2 - The Simon Game
- Dicee Game project.The Unix Command Line
-
kernel -> is core of operating system, the actual program that interfaces the hardware.
-
shel -> refers to user interface, for you as a human to be able to interact with kernel and in turn with the hardware of the computer.
-
there is two variants to shell:
- grafical user interface shell -> finder to find and access files is an example.
- command line interface.
-
Bash-sell -> Bourne again shell.
-
It is a CLI or command line interpretter for the UNIX system.
-
Using cmd bash-shell is easier and faster to do a lot of common things.
-
with cmd we have full control and more flexibility.
- Open up your hyper termial.
- ls a -> //shows all files including the hidden files.
- ls -> stands to list , prints all folders and files in the directory.
- ~ -> the root folder.
- cd /directory -> to navigate forwards to another directory.
- cd ../ -> to navigate backwords outside folder.
- when typing the first character of folder name and press tab it auto completes the name of directory.
- cd ~ -> go to the root directory.
- hit the up button to get the histoy of all commands.
- ctrl + a -> go to the beginning of line, ctrl + e -> go to the end of line.
- ctrl + u -> clear entire line.
- Some command lines:
- mkdir folderName -> //Creates a directory.
- cd folderName -> //change directory to the new folder created.
- touch fileName.extension -> //creates new file.
- start fileName.extension -> to open the file(open for mac).
- start -a Atom fileName.extension -> to open the file with Atom application for Example(use open for mac).
- rm fileName.extension -> removes the file.
- pwd -> show the current folder location (print working directory).
- rm * -> remove all files.
- rm -r folderName -> remove folder.
- Learn More about hyper terminal.
Backend Web Development
- Full-stack -> Front-end + Back-end.Node.js
18.1. What is Node.js?
- Allows us to create backend using javaScript.
- one language to make frontend and backend.
- nodejs: allows us to take js out of the browser and it librerates it allowing it to interact directely with the hardware of the computer.
- Sowe can make full application like descktop applications like atom with node(on our computer).
- we Can also run nodejs on server.
- Very fast programming language.
18.2. Install Node.js
18.3. The Power of the Command Line and How to Use Node
- $ pwd -> //print working directory
- $ cd -> //change directrory
- $ls -> //list of directroies and files
- $mkdir folderName -> //make directrory
- $touch fileName -> //make file
- $node file.js -> //usenode to run this file
18.4. The Node REPL (Read Evaluation Print Loops)
- Allows you to execute code in bite sized chunks(like console).
- By installing node we install it's REPL.
- $node -> //To run node REPL.
- crtl + c -> get out from any process.
- $ .exit -> // to exist the REPL(or twice crtl + c ).
- $ clear -> //clear commands
18.5. How to Use the Native Node Modules
- Libraries of code that the node team wrote.
- var creates variable.
- const -> can't change the value.
- file system module.
- In order to use module we have first to require it.
const fs = require('fs');
- Now we can use it in our project.
fs.copyFileSync('source.txt', 'destination.txt'); //copy source file into destination
18.6. The NPM Package Manager and Installing External Node Modules
- NPM -> Node Package Manager for External modules.
- Bits of reusable code that somebody wrote, and usine npm we can incorporate those packages into your project.
- When we install node we already install NPM.
- $npm init -y -> intailize NPM package.json file into the project.
- Example of npm package
Express.js with Node.js
19.1. What is Express?
- It's a Node framework.
- Built to make you write less repeatitive code.
- Express Documentation.
19.2. Creating Our First Server with Express
- open hyper terminal and Editor.
- Create new directory for the project $mkdir directory.
- cd into directory $ cd directory
- inside directrory make new file to start server from it $ touch index.js
- initialize npm $ npm init
- open project inside atom $ atom . .
- install express $ npm install express.
- require express:
const express = require('express')
const app = express()
app.listen(3000, () => {
console.log(`App listening at http://localhost:3000`)
})
- run server $ node index.js
19.. Handling Requests and Responses: the GET Request
- app.get -> define what happens ewhen someone makes a get request to the route on the first parameter.
- req -> the request that sent to the server.
- res -> the response that server send.
//Send the browser some information to display
app.get('/', (req, res) => {
res.send('Hello World!') //send text or html <h2>Hello World!</h2>
})
19.3. Nodemon Installation
- a npm package that auto start our servers.
- Once you install it, it will be available across your all projects.
- nodemon.
19.4. Understanding and Working with Routes
- You can set up as many routes as you wish.
app.get('/contact', (req, res) => {
res.send('Contact page')
})
app.get('/about', (req, res) => {
res.send('About page')
})
19.5. Calculator Setup Challenge
- Make a new folder called Calculator on your Desktop
- Change Directory to this new folder
- Inside the Calculator folder, create a new file called calculator.js
- Set up a new NPM package
- Open the project folder in Atom
- Using NPM install the express module
- Require express in your calculator.js
- Setup express
- Create a root route get method with app.get()
- Send the words Hello World from the root route as the response
- Spin up our server on port 3000 with app.listen
- Run server with nodemon
19.6. Calculator Setup: Challenge Solution
- $ mkdir Calculator
- $ cd Calculator
- $ touch calculator.js
- $ npm init
- $ atom .
- $ npm install express
Starter Code
- $ nodemon calculator.js
19.7. Responding to Requests with HTML Files
- make index.html file
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html')
})
19.8. Processing Post Requests with Body Parser
- Submit button sends the data into the form into the location(route) that at action attribute.
- List of HTTP status codes.
- In order to recieve post data from form we need to install package body-parser and require it, then we tell our app to use it.
require('express');
const bodyparser = require('body-parser')
const app = express()
app.use(bodyparser.urlencoded({extended : true}))
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html')
})
app.post('/', function(req, res){
console.log(req.body);
})
- It parses the req into text, so to convert to numder use Number(req.body.num).
19.9. BMI Routing Challenge
- Create a new file called bmiCalculator.html inside the Calculator folder from the last challenge
- Add the HTML boilerplate and set the page title to BMI Calculator
- Add an HTML form, this form will make a post request to our server at the route /bmicalculator. The form will have 2 inputs, weight and height with placeholder text that tell the user what they should type into which text box.
- Add a button which says “Caculate BMI”
- Add the get and post methods for the /bmicalculator route into the same server.js file we've been using
- Use sendFile() to send the bmiCalculator.html page as a response inside the get method.
- Add an h1 that says BMI Calculator
- Inside server.js , create 2 variables, one for weight and one for height.
- Use the BMI calculator code you wrote previously, or write some new code to calculate and send back the result as text. It should read something like "Your BMI is n" where n is equal to the calculated BMI based on their weight and height inputs.
19.10. Solution to the BMI Routing Challenge
app.get('/bmicalculator', function(req, res){
res.sendFile(__dirname + '/bmiCalculator.html')
})
app.post('/bmicalculator', function(req, res){
var weight = parseFloat(req.body.weight);
var height = parseFloat(req.body.height);
var bmi = weight / (height * height)
res.send("Your BMI is "+ bmi )
})
APIs - Application Programming Interfaces
20.1. Why Do We Need APIs?
- Application Programming Interfaces: is a set of command, functions, protocol and objects that prorammers can use to create software or interact with external system.
20.2. API Endpoints, Paths and Parameters.
- Endpoint: Every API that interacts with external server has endpoint "The url of the get request".
- Path: the word after the last (/) in the endpoint url.
- Parameters: the words at the end of url after (?) in the endpoint url
- consists of ?key=value, the first parameter after (?) and the rest of parameters sfter (&).
- The order of parameters dosen't matter.
- kanye API.
- Joke API.
20.3. API Authentication and Postman
- Authentication: Every time you make a request through the API, they have to be able to identify you as a developer and they have to keep track how often you use this API to get data, then charge you or limit you accordingly.
- weather API.
- sign up and sign in.
- API key and create a key.
- when we testing APIs we use Postman.
20.4. What is JSON?
- Stands for Javascript Object Notation.
- It's not the only data that can receive data from APIs.
- JSON vs XML.
- chrome extention JSON Viewer.
- The Rise and Rise of JSON.
20.5. Making GET Requests with the Node HTTPS Module
- Ways To make get request.
- Use native httpRequest Module.
- Require it but you don't need to insall it.
- HTTPS.
app.get('/', function(req, res){
//url parts
const query = 'london';
const apiKey = '3b712ebc109bc87b541a0abaa0f64b85';
const unit = 'metric';
//request from our Server to external server 'API'
const url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=${apiKey}&units=${unit}`;
https.get(url, function(response){
console.log((response));
})
})
20.6. How to Parse JSON
- All response.statusCode.
- statusCode for fun :).
- JSON.parse(jsonData) -> convert data to Object.
- JSON.stringfy(objectData) -> convert Object to Json.
app.get('/', function(req, res){
https.get(url, function(response){
//response from external Server to our server
response.on('data', function(data){
console.log(data);
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const weatherDescription = weatherData.weather[0].description
})
})
})
20.7. Using Express to Render a Website with Live API Data
- Only one res.send() is allowed in the same request.
//request from client to our server
app.get('/', function(req, res){
//request from our Server to external server 'API'
https.get(url, function(response){
//response from external Server to our server with data
response.on('data', function(data){
const icon = weatherData.weather[0].icon;
const iconUrl = `http://openweathermap.org/img/wn/${icon}@2x.png`;
console.log(weatherData + temp + weatherDescription + icon + iconUrl);
//response from our server to client server
res.write(`<p>The weather description is ${weatherDescription}</p>`)
res.write(`<h1>The Tempereture in ${query} is ${temp} in Celcuis Degrees. </h1>`)
res.write(`<img src="${iconUrl}" />`)
res.send()
})
})
})
20.8. Using Body Parser to Parse POST Requests to the Server
- create form to send city name from input.
- recieve that input data by body-parser module.
app.get('/', function(req, res){
//url parts
const query = req.body.cityName;
})
20.9. The Mailchimp API - What You'll Make
- Make Real website on web.
20.10. Setting Up the Sign Up Page
- Setting new project using node and express.
- $touch file1 file2 file3-> we can write more than one file with a single space between them.
- Use bootstrap to make styles and signup.html page.
- In order to make our server serve css files and imgages folders we need function called static('ourStaticFolder').
const bodyParser = require('body-parser')
const app = express() //make new instance from express
app.use(express.static("public"))
app.use(bodyParser.urlencoded({extends: true}))
app.get('/', function(req, res){
res.sendFile(__dirname + '/signup.html')
});
app.post('/', function(req, res){
const fName = req.body.fName;
const lName = req.body.lName;
const email = req.body.email;
})
20.11. Posting Data to Mailchimp's Servers via their API
- Mailchimp Getting Started.
- login to Mailchimp then create API key.
- Mailchimp List Documentation.
- Use list id (audiance id) to help Mailchimp to identify the list that you want to put your subscribers on it.
- To send data using https use https.request() and make it into a variable to send data from the form.
- url: 'https://.api.mailchimp.com/3.0/' -> the endpoint and path
- auth: 'anystring:<YOUR_API_KEY>' -> in https options there is auth.
app.post('/', function(req, res){
const data = {
members : [
{
//the value is from the form
email_address : email,
status: "subscribed",
merge_fields: {
FNAME: fName,
LNAME: lName
}
}
]
}
const jsonData = JSON.stringify(data);
const listId = "listId"
const url = `https://<dc>.api.mailchimp.com/3.0/lists/${listId}`
const options = {
method: 'POST',
auth: 'anystring:<YOUR_API_KEY>'
}
const request = https.request(url, options, function(response){
response.on('data', function(data){
console.log(JSON.parse(data));
})
}); //data recieved from external API
//data which is sent to an external API from the form
request.write(jsonData)
request.end()
});
20.12. Adding Success and Failure Pages
const request = https.request(url, options, function(response){
if(response.statusCode === 200){
res.sendFile(__dirname + '/success.html')
}else{
res.sendFile(__dirname + '/failure.html')
}
});
//Try Again
app.post('/failure', function(req, res){
res.redirect('/')
})
20.13. Deploying Your Server with Heroku
- Heroku.
- Heroku Node.js Documentation.
- To make app work locally and on heroku port.
app.listen(process.env.PORT || 3000, function(req, res){
console.log('Running at 3000 server.');
})
- Create a Procfile and declare what command should be executed to start your app inside it:
web: node app.js
- Use git:
- $ git init
- $ git add .
- $ git commit -m "Message"
- $ heroku create
- $ git push heroku master
- To update : use 1, 2, 3, 5 commands.
Git, Github and Version Control
21.1. Introduction to Version Control and Git
- Version Control: make you can Roll back to a previous versions of the project.
21.2. Version Control Using Git and the Command Line
- Download Git for Windows and Mac.
- $ git init
- $ git status //To see what currently in staging area.
- $ git add fileName // add file to the staging area
- $ git commit -m "Message" // Keep track of what changes you made
- $ git log // To see what commits you made
- Working directroy : is the folder where you inialize your Git.
- Staging area: intermediate area that the changes go there when typing $ git add command.
- Local directrory: changes go there after $ git commit command(.git file inside the project folder).
- $ git diff fileName // To see the difference between current file and the last versions.
- $ git checkout fileName // roll back to the last version
21.3. GitHub and Remote Repositories
- Make project repository on github.
- $ git remote add origin repositoryUrl
- $ git push -u origin master
- Master branch: is the main branch of commits.
- Remote directory: which host our code and host all the changes that made after $ git push command(Github Repository).
21.4. Gitignore
- $ git rm --cached -r . // remove all files
- Gitignore and the absence of NPM Modules on GitHub Projects.
21.5. Cloning
- Is a way to pull down all of the commits and all of the versions of a particular remote repository and store the files inside your working directory.
- $ git clone repositoryUrl
21.6. Branching and Merging
- $ git branch branchName // Creates new branch
- $ git branch // check out what branches you have and show where you are
- $ git checkout branchName // To switch to this branch
- To merge go back to master branch: $ git branch master
- Then merge: $ git merge branchName.
- it will open vim to maje merge message(write :q! to exit vim)
- $ git push -u origin master
21.7. Optional Git Challenge
21.8. Forking and Pull Requests
- forking: make a copy of the project from remote repository
- pull: make a request to push changes into the main project remote repository.
- if the pull request is approved, changes will be merged to the main project.
EJS
- Make todolist-v1.
- we need templates to can change certain part in html depends on our logic.
- EJS documentation
- $ npm i ejs
- use it with express ->
app.use('view engine', 'ejs')
- make views folder and put html files inside it(use .ejs instead of .html).
- use
res.render('page', {key: value})
instead ofres.send('page')
. - inside page.ejs file we use the
<%= key %>
to get the value.
- scriptlet tag
<% %>
-> for control flow inside pages, it must be around anything that is not html line by line(for each line of js).
<% if(condition){ %>
//Do something
//html code
<% } else { %>
//Do something else
<% } %>
- format date ->
toLocaleDateString('region', options)
. - To send data from form to page:
- make
app.post()
to save data from the form into global varible or push it into global array and redirect to the page route. - recive the variable into page
app.get()
and send it inside render object.
- make
- To render array of items, we loop throw it inside ejs page.
- local variables -> the scope of local variables is local to where they were declared.
- Global variables -> Global to all scopes inside the code.
- var -> inside for loop, if, and eny block which is not a function, variable which is declared with var keyword is accessable outside it(Global).
- let, const -> inside for loop, if, and eny block which is not a function, are local.
- const -> value can't be changed.
- var -> inside for loop, if, is global variable.
- var, let, const -> outside a function they all are global variables.
- var, let, const -> inside a function they all are local variables.
- In order to access the css file for our website, we have to tell express explicitly to serve up the css files, and we need to tell it the location our file and tell it to use it.
- create public folder as a static resource and add
app.use(express.static('public'))
. - public folder contains css, images files.
- make
/work
directory to use the same homepage layout with different directroies. - change
value
attribute of the form button to the page title, to handle submit event. - make header.ejs, footer.ejs and include it into pages
<%- include('header') -%>
.
- Export Module in Node.js.
module.exports
is equal toexports
.- const keyword
Boss Level Challenge 3 - Blog Website
- Project ejs-challenge.Databases
- We need databases to store the data.
- SQL databases: Stands for Structured Query language.
- NOSQL databases: Stands for Not Only Structured Query language.
- Depending on the structure of your data you will want to choose a SQL or a NOSQL database.
- If you need to store data such as orders, customer details, products thing that have lots of relationships between each other, then you might be better to choose SQL such is MySQL.
- If you have a website where you have something that's more of a one to many kind of relationships, this much easier to store data using NOSQL such as MongoDB.
SQL
- Every database doing CRUD operations (Create, Read, Update, Delete).
- w3schools
- DB Edittor
- To Create new DB Table (Create):
CREATE TABLE Products (
ID int NOT NULL,
name varchar(255) NOT NULL,
price int,
PRIMARY KEY (ID)
);
- The PRIMARY KEY constraint uniquely identifies each record in a table.
- To insert into table:
INSERT INTO Products
VALUES (1, "pencil", 10);
- To Read from DB table(Read):
SELECT * FROM Products
WHERE id='1';
- The
*
Means everthing inside the table. WHERE
Followed by the condition.=
Operator withWHERE
, There is many other operators such as>, <, >=, ...etc
.
- To Update the table record:
UPDATE Products
SET name = "pen", price = 20
WHERE id=1;
- Without
WHERE
statement, it will update every record. - To update the table columns:
ALTER TABLE Products
ADD stock INT;
- To Delete:
DELETE FROM Products WHERE id=1;
- A FOREIGN KEY is a key used to link two tables together.
CREATE TABLE Orders (
orderID INT NOT NULL,
orderNumber INT NOT NULL,
customerID INT,
productID INT,
PRIMARY KEY (OrderID),
FOREIGN KEY (customerID) REFERENCES customers(id)
);
- To join tables:
SELECT Orders.OrderID, Customers.first_name, Customers.last_name
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.id;
MongoDB
26.1. Installing MongoDB on Windows
- Go to mongodb to dowload it.
- Install MongoDB
26.2. MongoDB CRUD Operations in the Shell: Create
-
$ mongod
-> To start mongo DB server. -
$ mongo
-> To start mongo shell. - In the shell ->
$ help
: shows list of help cmds. -
$ show dbs
-> shows all existed dbs. -
$ use shop
-> To create new db called shop. - New db
shop
to be listed inside dbs, it must have some data. -
$ db
-> To know what db you currently worked in. - MongoDB Docs on CRUD operations.
-
$ db.propducts.insertOne({_id:1, name:"pen", price: 10})
-> if thatpropducts
collection doesn't exist in the db, then it will create that collection. - The collections in mongoDB is similler to tables in the SQL.
-
$ show collections
-> show all collections in the current db.
26.3. MongoDB CRUD Operations in the Shell: Reading & Queries
-
$ db.propducts.find()
-> To Read all documents that is insidepropducts
collection. -
$ db.propducts.find({_id: 1})
-> find the document which has id equal to1
. -
$ db.propducts.find({_id: {$gt: 1})
-> find all the documents which has id greater than1
. -
$ db.propducts.find({_id: 1}, {name: 1, _id:0})
-> find the document which has id equal to1
, and give only thename
. - The second parameter in find method specify which feild to return.
26.4. MongoDB CRUD Operations in the Shell: Update
-
$ db.propducts.updateOne({_id: 1}, { $set: { stock: 12 })
-> update id1
, addstock
feild.
26.. MongoDB CRUD Operations in the Shell: Delete
-
$ db.propducts.deleteOne({_id: 2})
-> delete record2
.
26.5. Relationships in MongoDB
- One to many relationship:
$ db.propducts.insertOne(
_id: 3,
name: "rubber",
stock: 20,
reviews: [
{
auther: "Mai",
rating: 5,
review: "Best Rubber!"
},
{
auther: "Angela",
rating: 4,
review: "Awesome!"
},
{
auther: "Ahmed",
rating: 3,
review: "Nice!"
}
]
)
26.6. Working with The Native MongoDB Driver
Mongoose
27.0 Mongoose version reference
-
Reference from stack overflow - Model.find() no longer accepts a callback in Mongoose
-
The latest version is 7.0.3 but we use 5.3.4 in the courese. Thus, you might need to install
npm install mongoose@5.3.4
insted ofnpm install mongoose
-
If use the latest version, the user may face
MongooseError: Model.insertMany() no longer accepts a callback @7.0.3
27.1. Introduction to Mongoose
- Mongoose: an alternative to the native MongoDB driver
-
$ mongod
-> To start mongo DB server. -
$ mongo
-> To start mongo shell. -
$ show dbs
-> shows all existed dbs. -
$ use fruitDB
-> switch to fruitDB. -
$ db.dropDatabase()
-> drop switched db. -
$ npm i mongoose
-> Install mongoose into fruits folder. -
$ show collections
-> show db collections. -
$ db.fruits.find()
-> show everything inside fruits collection. - To create new collection and document:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fruitsDB', {
useNewUrlParser: true
});
const fruitsSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
color: String,
rating: {
type: Number,
min: 0,
max: 5
}
})
const Fruit = mongoose.model('Fruit', fruitsSchema)
const kiwi = new Fruit({
name: "Kiwi",
color: "Green",
rating: 1
})
- Mongoose documentation on the Model.
- To insert documents into db:
Fruit.insertMany([apple, kiwi, banana], function(error){
if(error){
console.log(error);
}else{
console.log("Successfully added to DB");
}
})
27.2. Reading from Your Database with Mongoose
- To find all documents in specific collection:
Fruit.find(function(error, fruits){
if(error){
console.log(error);
}else{
fruits.forEach(fruit => {
console.log(fruit.name);
mongoose.connection.close() // To close connection without have to press ctrl + c
})
}
})
27.3. Data Validation with Mongoose
const fruitsSchema = new mongoose.Schema({
rating: {
type: Number,
min: 0,
max: 5
}
})
27.4. Updating and Deleting Data Using Mongoose
- Update and delete One record:
Fruit.updateOne({_id: "5fa0397233b60415cc755db4"}, {name: 'Watermelon'}, function(error, res){
if(error){
console.log(error);
}else{
console.log("Successfully Updated");
}
})
Fruit.deleteOne({_id: "5fa05cfa7cc59f34408b9bb0"}, function(error){
if(error){
console.log(error);
}else{
console.log("Successfully Deleted");
}
})
- Delete many records:
Peaple.deleteMany({name: "Mai"}, function(error){
if(error){
console.log(error);
}else{
console.log("Successfully Deleted");
}
})
27.5. Establishing Relationships and Embedding Documents using Mongoose
const fruitsSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
color: String,
rating: {
type: Number,
min: 0,
max: 5
}
})
const peopleSchema = new mongoose.Schema({
name: String,
age: Number,
favFruits: fruitsSchema
})
const pineapple = new Fruit({
name: "Pineapple",
color: "light green",
rating: 4
})
const person1 = new Peaple({
name: "John",
age: 30,
favFruits: pineapple
})
Putting Everything Together
-
Update todoList project to connect to Mongodb.
-
Removing items from an array with the MongoDB $pull operator.
Deploying Your Web Application
- Put the app into internet so that everybody can access it.
- Heroku host our node application instead our localhost
http://localhost:3000
. - Mongodb atlas hosr our database.
- heroku is able to make requestes to atlas server then get data from it.
Boss Level Challenge 4 - Blog Website Upgrade
- Update Blog project to connect to Mongodb.Build Your Own RESTful API From Scratch
31.1. What is REST?
- REST stands for Representational State Transfer
- REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.
- GET(READ), POST(CREATE), PUT(UPDATE), PATCH(UPDATE), DELETE.
- PATCH: sending a piece of data that needs to be updated, instead of the entire entery.
- We use different routes in order to access certain resources.
31.2. Creating a Database with Robo 3T
- Robo 3T Github
- Official website.
- make db collection and add some articles to it.
31.3. Set Up Server
-
$ mkdir wiki-Api
-> Make a new folder calledwiki-Api
on your Desktop -
$ cd wiki-Api
-> Change Directory to this new folder -
$ touch app.js
-> Inside thewiki-Api
folder, create a new file calledapp.js
-
$ npm init -y
-> createpackage.json
file. -
$ npm i express ejs body-parser mongoose
-> Set up a new NPM packages. -
$ Atom .
-> Open the project folder in Atom -
$ nodemon app.js
-> Run server with nodemon - Set starting code:
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static("public"));
//Connect to mongoose db
mongoose.connect('mongodb://localhost:27017/wikiDB', {useNewUrlParser: true});
const articleSchema = new mongoose.Schema({
title: String,
content: String
})
const Article = mongoose.model('Article', articleSchema)
app.listen(3000, function() {
console.log("Server started on port 3000");
});
31.3. GET All Articlesmongoose
- Get all articles:
app.get('/articles', function(req, res){
Article.find({}, function(error, foundArticles){
if(error){
res.send(error);
}else{
res.send(foundArticles);
}
});
})
31.4. POST a New Article
- Use postman to post and test data without need to frontend form.
app.post('/articles', function(req, res){
const article = new Article({
title: req.body.title,
content: req.body.content
})
article.save(function(error){
if(error){
res.send(error)
}else{
res.send("Successfully added.")
}
});
})
31.5. DELTE All Articles
- Delete all articles when make DELETE request with postman:
app.delete('/articles',function(req, res){
Article.deleteMany(function(error){
if(!error){
res.send("Successfully Deleted")
}
});
})
31.6. Chained Route Handlers Using Express
31.7. GET a Specific Article
app.route('/articles/:articleTitle')
.get( function(req, res){
const articleTitle = req.params.articleTitle
Article.findOne({title: articleTitle}, function(error, foundArticle){
if(foundArticle){
res.send(foundArticle)
}else{
res.send("No Mathed article!")
}
});
})
- localhost:3000/articles/Jack%20Bauer === "Jack Bauer"
31.8. PUT a Specific Article
.put(function(req, res){
Article.update(
{title: req.params.articleTitle},
{title: req.body.title, content: req.body.content},
{overwrite: true},
function(error){
if(!error){
res.send()
}
}
)
})
31.9. PATCH a Specific Article
.patch(function(req, res){
Article.update(
{title: req.params.articleTitle},
{$set: req.body},
function(error){
res.send(error || 'Successfully Updates.')
}
)
})
31.10. DELETE a Specific Article
.delete(function(req, res){
Article.deleteOne({title: req.params.articleTitle}, function(error){
res.send(error || 'Successfully Deleted Corresponding article.')
})
})
Authentication & Security
- why we need Authentication?
- In order to associate pieces of data with users we need an account.
- To restrict access, like Payment processes.
- There is 6 different levels of security.
- Dowload starter code of
Secret
project and setting up our app.
- Creating user account and Storing email and password into database and check if they exist in db.
- Create user database.
- That step stores password into plain text into database(very bad practise).
- Encryption is the process of encoding information. This process converts the original representation of the information, known as plaintext, into an alternative form known as ciphertext. Ideally, only authorized parties can decipher a ciphertext back to plaintext and access the original information.
- cryptii.
- Install and use mongoose-encryption package.
- It's important to add plugin to schema before creating a model.
- Install dotenv to make
.env
file. - Configre it at the top ->
require('dotenv').config()
. - create
.env
file and addSECRET=OurStringSecret
. - Use this string in
app.js
->process.env.SECRET
.
- Hashing performs a one-way transformation on a password, turning the password into another String, called the hashed password. “One-way” means that it is practically impossible to go the other way - to turn the hashed password back into the original password. There are several mathematically complex hashing algorithms that fulfill these needs.
- Use md5 package to hash password.
- When you think of your password as an mathmatical formula, you realize that as long as your password, the computation time that takes to hack this password increases exponentially.
- Hacker Typer :"D .
- Salting involves adding random data before it is put through a cryptographic hash function.
- With "salt round" they actually mean the cost factor. The cost factor controls how much time is needed to calculate a single BCrypt hash. The higher the cost factor, the more hashing rounds are done. Increasing the cost factor by 1 doubles the necessary time. The more time is necessary, the more difficult is brute-forcing.
- bcrypt.
- To change node version we need to install
nvm
.
const bcrypt = require('bcrypt')
const saltRounds = 10
- Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as a server.
- A session ends when the user closes the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
- A session is a type of cookie. It is a period of time when a browser interact with server.
- Cookies in Chrome
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
//Connect to mongoose db
mongoose.connect('mongodb://localhost:27017/usersDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.set('useCreateIndex', true)
//initailze session and passport
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize())
app.use(passport.session())
...
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
secret: String
})
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model('User', userSchema)
//This three lines From passport-local-mongoose
passport.use(User.createStrategy());
//Enables passport to Create cookie(Start Session)
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// Destroy Cookie(End session)
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.get('/secrets', function(req, res) {
User.find({'secret': {$ne: null}}, function(error, foundUser){
if(error){
console.log(error);
}else{
if(foundUser){
res.render('secrets', {usersWithSecret: foundUser})
}
}
})
})
app.get('/register', function(req, res) {
res.render('register')
})
// Authenticate user and Start session
app.post('/register', function(req, res) {
User.register({
username: req.body.username
}, req.body.password, function(error, user) {
if (error) {
console.log(error);
res.redirect('/register')
} else {
passport.authenticate('local')(req, res, function() {
res.redirect('/secrets')
})
}
})
})
app.post('/login', function(req, res) {
const user = new User({
username: req.body.username,
password: req.body.password
})
req.login(user, function(error) {
if (error) {
console.log(error);
} else {
passport.authenticate('local')(req, res, function() {
res.redirect('/secrets')
})
}
})
})
// Deauthenticate user and end session
app.get('/logout', function(req, res) {
req.logout()
res.redirect('/')
})
- Whenever the server gets restarted, the cookies gets deleted and the session gets restarted.
-
OAuth: commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Amazon,[2] Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.
-
"Third party" has a similar meaning as third person, except in the perspective of computer stuff, the “persons” change in something like the following fashion:
- First “party” - the software itself, or the logical “I”.
- Second “party” - the user of the software, or the logical “You”.
- Third “party” - other pieces of software in the environment, or the logical “They”.
var findOrCreate = require('mongoose-findorcreate');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
...
userSchema.plugin(findOrCreate);
...
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
// FindorCreate not mongoose function, it's a description
// To make it work we installed mongoose-findorcreate plugin
User.findOrCreate({
googleId: profile.id
}, function(err, user) {
return cb(err, user);
});
}
));
- mongoose-findorcreate: Simple plugin for Mongoose which adds a findOrCreate method to models. This is useful for libraries like Passport which require it.
- Goole id prevent creating the same user again when sign up or login with google.
- Add
/submit
route to show users secrets on/secrets
page.
React.js
- Take a look on projects that we will build.
- Start
- End
- Write any html attribute in the camel Case.
- Standard HTML attributes
- Lorem Picsum
- One reasons to use inline styles is if we want to change style of element based on action.
- With jsx, The
style
attribute requires value as a javascript Object. - Write any css properity in camel case.
- Node
- Babel syntax highlighting for code editors
- Create a new react app
- Where to get support if you get stuck
- Start
- Synthetic Events
- Never use the
event
inside state hooks methods, because that react passes a synthaticevent
not a real event. - End