Documente Academic
Documente Profesional
Documente Cultură
//For define a pattern where we listen for a get request to slash or slash anything else afterwards any
single subname put colon and tells express to not actually match character.put a colon front of anything
,will be able to change.
Example1:
var express = require("express");
var app = express();
app.get("/", function(req, res){ res.send("Hi there!");});
app.get("/bye", function(req, res){ res.send("Goodbye!!"); });
app.get("/dog", function(req, res){ res.send("MEOW!"); });
app.get("/r/:subredditName", function(req, res){
var subreddit = req.params.subredditName;
res.send("WELCOME TO THE " + subreddit.toUpperCase() + " SUBREDDIT!");
});
app.get("/r/:subredditName/comments/:id/:title/", function(req, res){
console.log(req.params);
res.send("WELCOME TO THE COMMENTS PAGE!");
});
app.get("*", function(req, res){ //will overrides any of other routes
res.send("YOU ARE A STAR!!!");
});
// Tell Express to listen for requests (start server)
app.listen(3000, function(){
console.log("Server has started!!!");
});
Template and Ejs:
User res.render() to render HTML(from an ejs file). EJS or Embedded Javascript Templating is a
templating engine used by Node.js. Template engine helps to create an HTML template with minimal
code. Also, it can inject data into HTML template at the client side and produce the final HTML. EJS is a
simple templating language which is used to generate HTML markup with plain JavaScript. It also helps
to embed JavaScript to HTML pages. To begin with, using EJS as templating engine we need to install EJS
using given command:
npm install ejs --save
*****To add dynamic content this render method takes a second parameter which is an object.
res.render(‘home’,{name:’silvia’});
Example2:
var express = require("express");
var app = express();
app.use(express.static("public"));
app.set("view engine", "ejs")
app.get("/", function(req, res){ res.render("home"); });
app.get("/fallinlovewith/:thing", function(req, res){
var thing = req.params.thing;
res.render("love", {thingVar: thing});
});
app.get("/posts", function(req, res){
var posts = [
{title: "Post 1", author: "Susy"},
{title: "My adorable pet bunny", author: "Charlie"},
{title: "Can you believe this pomsky?", author: "Colt"}
];
res.render("posts", {posts: posts});
})
Example 3:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
var friends = ["Tony", "Miranda", "Justin", "Pierre", "Lily"];
app.get("/", function(req, res){
res.render("home");
});
app.post("/addfriend", function(req, res){
var newFriend = req.body.newfriend;
friends.push(newFriend);
res.redirect("/friends");
});
app.get("/friends", function(req, res){
res.render("friends", {friends: friends});
});
app.listen(3000, function(){
console.log("Server started!!!");
});
Friends.ejs:
<h1>Friends List Goes Here!</h1>
<% friends.forEach(function(friend){ %>
<li><%= friend %></li>
<% }); %>
<form action="/addfriend" method="POST">
<input type="text" name="newfriend" placeholder="name">
<button>I made a new friend!</button>
</form>
Home.ejs:<h1>home page</h1>
----------------------------------------------------END-------------------------------------------------
******req.body::req.body is an obj that will contain all of the data from
request body.
Form that making a post request .All the form data is put in the request body
and then it gets to our express app and we want to pull it out of the request
body.Express out of the box doesn’t actually create req.body for us.Need
explicitely tell it to take request body and turn it into a javascript obj .
So to do that we actually need to install body-parser.
******npm install body-parser . By default, it is undefined, and is populated when you use
body-parsing middleware such as body-parser
******bodyParser.urlencoded({extended: true})->middleware for parsing bodies from
URL
Example4:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
var friends = ["Tony", "Miranda", "Justin", "Pierre", "Lily"];
app.get("/", function(req, res){
res.render("home");
});
app.post("/addfriend", function(req, res){
var newFriend = req.body.newfriend;
friends.push(newFriend);
res.redirect("/friends");//will take the name of route ,will redirect to this route
});
app.get("/friends", function(req, res){
res.render("friends", {friends: friends});
});
app.listen(3000, function(){
console.log("Server started!!!");
});
Views/friends.ejs:
<h1>Friends List Goes Here!</h1>
<% friends.forEach(function(friend){ %>
<li><%= friend %></li>
<% }); %>
<form action="/addfriend" method="POST">
<input type="text" name="newfriend" placeholder="name">
<button>I made a new friend!</button>
</form>
API stands for Application Programming Interface (main participant of all the interactivity)
It is like a messenger that takes our requests to a system and returns a response back to us via
seamless connectivity.
We use APIs in many cases like to get data for a web application or to connect to a remote
server that has data like weather that keeps changing or to enable two applications to exchange
data among each other.
API not only provide reusability of code but also uses the concept of Abstraction (showing
functionality by hiding complexity).
Most common real life use of API concepts include:
Waiter in a restaurant taking your order request to the chef and bringing back the requested
dish
Switchboard turning off the tubelight just on a single press
Booking a flight online from sites like MMT(web based)
Signing up in a shopping site from Facebook Account(web based)
Different APIs will communicate in different ways:
XML-RCP/SOAP: Both uses XML
JavaScript: Focused around Javascript
RESTful APIs: HTTP protocol (HyperText Transfer Protocol) used (best for web APIs)
///API doesn’t respond with HTML.API respond with data ,not structure.
HTML->structure of page info.
So use simpler data formats XML and JSON
Both JSON and XML can be used to receive data from a web server.
Making API request with node:
Make a request through code using a package called request.
Request is designed to be the simplest way possible to make http calls. It
supports HTTPS and follows redirects by default.
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
///callback function is needed to do anything with the information that comes back.error-
>server does is down or the request times out or have no internet.
url will make request.
///body ::when its back ,its like a javascript obj. but it’s a string.
///typeof body is used to see that it’s a .console.log(typeof body)
ʆ: error
null
ʆ: response:all kinds of information available.
ʆ:response.statusCode 200
ʆ:JSON.parse(body)
##console.log(parseddata.name+’lives in’+parseddata.address.city);
##console.log(`${parseddata.name} lives in ${parseddata.address.city}`);//same task done .
Var ->const.
request('https://jsonplaceholder.typicode.com/users/1', (error, response, body)=>{:::::arrow function
https://gemfury.com/squarecapadmin/js:request-promise npm i request-promise
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
Example:
const rp=require('request-promise');
rp('https://jsonplaceholder.typicode.com/users/1')
.then((body)=> {
//console.log(htmlstring);
const parseddata=JSON.parse(body);
console.log(`${parseddata.name} lives in ${parseddata.address.city}`);
})
.catch((err)=>{
console.log('Error!',err);
});
-------------------------------------------------END----------------------------------------------------------
Movie API:
General search: http://www.omdbapi.com/?s=guardians+of+the+galaxy&apikey=thewdb
Search with Movie ID: http://www.omdbapi.com/?i=tt3896198&apikey=thewdb
http://omdbapi.com/
Results route:
var express = require("express");var app = express();var request = require("request");
app.set("view engine", "ejs");
app.get("/results", function(req, res){
request("http://omdbapi.com/?apikey=thewdb&s=california", function(error, response, body){
if(!error && response.statusCode == 200) { res.send(body); } });});
app.listen(3000, function(){
console.log("Movie App has started!!!");});
///res.send(body[“Search”][0]);//undefined .cause it’s a string.so convert it into an object.
app.get("/results", function(req, res){
request("http://omdbapi.com/?apikey=thewdb&s=california", function(error, response, body){
if(!error && response.statusCode == 200) {
var results=JSON.parse(body);
res.send(results["Search"][0]["title"]);
} });});
---------------------------------------------------------------END----------------------------------------------------------------------
Displaying and searching:
Search.ejs:
<ul><%data["Search"].forEach(function(movie){%>
<li><strong><%=movie["Title"]%></strong> -<%=movie["Year"]%></li><%})%></ul>
<a href="/">search again</a>
Results.ejs
<form action="/results" method="GET">
<input type="text" placeholder="search-item" name="search">
<input type="submit"></form>
App.js
var express = require("express");var app = express();var request = require("request");
app.set("view engine", "ejs");
app.get("/", function(req, res){res.render("search");});
app.get("/results", function(req, res){
var query = req.query.search;//req.params contains route parameters (after path portion in url )and
req.query contains url query parameters(after ? in the url)
var url = "http://omdbapi.com/?apikey=thewdb&s=" + query;
request(url, function(error, response, body){ if(!error && response.statusCode == 200) {
var data=JSON.parse(body);res.render("results",{data:data});} });});
app.listen(3000, function(){
console.log("Movie App has started!!!");
});
-------------------------------------------------------------END------------------------------------------------------------------------
Yelpcamp:
var express = require("express");var app = express();var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));app.set("view engine", "ejs");
var campgrounds = [
{name: "Salmon Creek", image: "https://farm9.staticflickr.com/8442/7962474612_bf2baf67c0.jpg"},
{name: "Granite Hill", image: "https://farm1.staticflickr.com/60/215827008_6489cd30c3.jpg"} ];
app.get("/", function(req, res){ res.render("landing");});
app.get("/campgrounds", function(req, res){ res.render("campgrounds",{campgrounds:campgrounds});});
app.post("/campgrounds", function(req, res){ // get data from form and add to campgrounds array
var name = req.body.name; var image = req.body.image; var newCampground = {name: name, image: image}
campgrounds.push(newCampground); res.redirect("/campgrounds");});
app.get("/campgrounds/new", function(req, res){res.render("new.ejs"); });
app.listen(3000, function(){ console.log("The YelpCamp Server Has Started!");});
Views/partials/header.ejs:
<!DOCTYPE html><html><head>
<title>YelpCamp</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head> <body>
<nav class="navbar navbar-default"><div class="container-fluid"> <div class="navbar-header">
<a class="navbar-brand" href="/">YelpCamp</a> </div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="/">Login</a></li> <li><a href="/">Sign Up</a></li> <li><a href="/">Logout</a></li>
</ul></div></div></nav>
Views/campgrounds.ejs
<%- include(“../ partials/header “%>
<div class="container"><header class="jumbotron"><div class="container">
<h1>Welcome To YelpCamp!</h1>
<p>View our hand-picked campgrounds from all over the world</p>
<p><a class="btn btn-primary btn-large" href="/campgrounds/new">Add New Campground</a></p>
</div> </header>
<div class="row text-center" style="display:flex; flex-wrap: wrap;">
<% campgrounds.forEach(function(campground){ %>
<div class="col-md-3 col-sm-6">==<div class="thumbnail"><img src="<%= campground.image %>">
<div class="caption"><h4><%= campground.name %></h4>
</div> </div></div> <% }); %> </div></div>
<%- include(“../ partials/footer“)%>
View/landing.ejs:
<%- include(“../ partials/header“)%>
<h1>Landing Page!</h1>
<p>Welcome to YelpCamp</p>
<a href="/campgrounds">View All Campgrounds</a>
<%- include(“../ partials/footer“)%>
Views/new.ejs:
<%- include(“../ partials/header“)%>
<div class="container"><div class="row”> <h1 style="text-align: center">Create a New Campground</h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/campgrounds" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="name" placeholder="name"</div>
<div class="form-group">
<input class="form-control" type="text" name="image" placeholder="image url"></div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">Submit!</button></div> </form>
<a href="/campgrounds">Go Back</a> </div></div></div>
<%- include(“../ partials/footer“)%>
-----------------------------------------------------------END--------------------------------------------------------------
Mongoshell Basics:
mongo:
help:
show dbs:
use nameofthedatabase:
use databasename:
show dbs:
->db.dogs.insert({name:”jon”,breed:”jon”})
Show collections:
->db.dogs.find()
->db.dogs.find({name:”----“,breed:”-----“})
->db.dogs.update({name:”-----“},{breed:”----“})//first parameter is select attribute name
->db.dogs.remove({breed:”---“}).limit(1)
var catSchema = new mongoose.Schema({//this pattern says every cat has a name and age and temperament
name: String, age: Number, temperament: String}); ///it’s a obj//compiled it into a model
var Cat = mongoose.model("Cat", catSchema);
//adding a new cat to the DB
var george = new Cat({ name: "Mrs. Norris", age: 7, temperament: "Evil" });
george.save(function(err, cat){ if(err){ console.log("SOMETHING WENT WRONG!") }
else { console.log("WE JUST SAVED A CAT TO THE DB:")console.log(cat); }});
Cat.create({ name: "Snow White", age: 15, temperament: "Bland"}, function(err, cat){
if(err){ console.log(err); } else {console.log(cat); }});
//retrieve all cats from the DB and console.log each one
Cat.find({}, function(err, cats){
if(err){ console.log("OH NO, ERROR!"); console.log(err); }
else {console.log("ALL THE CATS....."); console.log(cats); }});
----------------------------------------------------------------END-----------------------------------------------------------------------------------
Associations:
One:one,one:many and many:one relationship
Allow to have multiple pieces of data collections in database.
##1:var express= require("express”),app = express, bodyParser = require("body-parser"),mongoose
= require("mongoose");
//CONNECTING AND CREATING DATBASE:mongoose.connect("mongodb://localhost/associations", {
useNewUrlParser: true, useUnifiedTopology: true });
//SCHEMA SETUP
var postSchema = new mongoose.Schema({
title:String, content: String });
//converting into model And save into post variable
var Post = mongoose.model("post",postSchema);
// SCHEMA SETUP
var userSchema = new mongoose.Schema({
email:String,name: String, posts:[postSchema]
});
//converting into model and save into User variable
var User = mongoose.model("User",userSchema);
////new user email and name are creating:
var newUser=new User({
email:"silviaplabon@gmail.com",
name:"silvia satoar plabon"
})
////in newUser posts array pushing title and content
newUser.posts.push({
title:"silvia",
content:"sjdsjdjjjjjjjj"
})
////in newUser pushing data are saving
newUser.save(function(err,User){
if(err){console.log(err); }
else{console.log(User); }
});
app.listen(3000,function(){
console.log("The YelpCamp Started!!");
});
##2
User.create({
email:"silviaplabon@gmail.com",
name:"silvia plabon"
});
Post.create({
title:"plabon is a good and great man",
content:"silvia you are awesome"},function(err,post){
//creating Post data title and content and try to finding data
User.findOne({email:"silviaplabon@gmail.com"},function(err,founduser){
if(err){ console.log(err); }
else{ founduser.posts.push(post);
//pushing into posts array and saving
founduser.save(function(err,data){
User.findOne({email:"silviaplabon@gmail.com"},function(err,founduser){
if(err){ console.log(err); }
else{ console.log(data);}
}); });} }); })
//for getting shorted code:
var post=require("./models/post.js")//app.js
var mongoose=require("mongoose");//post.js
var postSchema = new mongoose.Schema({
title:String,
content: String,
});
module.exports= mongoose.model("post",postSchema);
var User=require("./models/user.js")//app.js
var userSchema = new mongoose.Schema({//User.js
email:String,name: String, posts:[postSchema],
});
module.exports= mongoose.model("User",userSchema);
User.findOne({name: "Hermione Granger"}, function(err, user){
if(err){ // console.log(err); }
else { user.posts.push({ title: "3 Things I really hate", content: "Voldemort. Voldemort. Voldemort"});
user.save(function(err, user){
if(err){ console.log(err); }
else { console.log(user); }
});}});
-------------------------------------------------------------------END---------------------------------------------------------------
models/post.js
var mongoose = require("mongoose");// POST - title, content
var postSchema = new mongoose.Schema({
title: String, content: String });
module.exports = mongoose.model("Post", postSchema);
models/user.js
var mongoose = require("mongoose");// USER - email, name
var userSchema = new mongoose.Schema({
email: String,name: String,
posts: [{
type: mongoose.Schema.Types.ObjectId, ref: "Post"
}]});
module.exports = mongoose.model("User", userSchema);
//requiring routes
var commentRoutes = require("./routes/comments"),
campgroundRoutes = require("./routes/campgrounds"),
indexRoutes = require("./routes/index")
mongoose.connect("mongodb://localhost/yelp_camp_v10");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
// seedDB(); //seed the database
// PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "Once again Rusty wins cutest dog!",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use("/", indexRoutes);
app.use("/campgrounds", campgroundRoutes);
app.use("/campgrounds/:id/comments", commentRoutes);
module.exports = router;
routes/comments.js:
//Comments New
router.get("/new",middleware.isLoggedIn, function(req, res){
// find campground by id
console.log(req.params.id);
Campground.findById(req.params.id, function(err, campground){
if(err){
console.log(err);
} else {
res.render("comments/new", {campground: campground});
}
})
});
//Comments Create
router.post("/",middleware.isLoggedIn,function(req, res){
//lookup campground using ID
Campground.findById(req.params.id, function(err, campground){
if(err){
console.log(err);
res.redirect("/campgrounds");
} else {
Comment.create(req.body.comment, function(err, comment){
if(err){
console.log(err);
} else {
//add username and id to comment
comment.author.id = req.user._id;
comment.author.username = req.user.username;
//save comment
comment.save();
campground.comments.push(comment);
campground.save();
console.log(comment);
res.redirect('/campgrounds/' + campground._id);
}
});
}
});
});
module.exports = router;
var express = require("express");
var router = express.Router();
var passport = require("passport");
var User = require("../models/user");
//root route
router.get("/", function(req, res){
res.render("landing");
});
// logout route
router.get("/logout", function(req, res){
req.logout();
res.redirect("/campgrounds");
});
//middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;
models/campground.js:
var mongoose = require("mongoose");
UserSchema.plugin(passportLocalMongoose)
module.exports = middlewareObj;
public/stylesheets/main.css: .thumbnail img {
width: 100%;
}
.thumbnail {
padding: 0;
}
.thumbnail .caption-full {
padding: 9px;
}
#delete-form {
display: inline;
}