Sunteți pe pagina 1din 28

Express:

Allows to set up middlewares to respond to HTTP Requests.


Defines a routing table which is used to perform different actions based on HTTP Method and URL.
Allows to dynamically render HTML Pages based on passing arguments to templates.
Installing Express: npm install express –save
const express = require('express')
const app = express()//express has lots of different methods so we cant’t execute express() like
this,var app=express();
app.get('/', function (req, res) { res.send('Hello World') })
app.listen(3000)
Package.json
npm init <initializer> can be used to set up a new or existing npm package.
npm has lots of packages that people want to use over and over again. package.json provides a simple
way for people to keep track of packages they use in their application.(shopping list for all packages)
The GET Method
GET is used to request data from a specified resource.
GET is one of the most common HTTP methods.
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests are only used to request data (not modify)
The POST Method
POST is used to send data to a server to create/update a resource.
The data sent to the server with POST is stored in the request body of the HTTP request:
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length

//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});
})

app.listen(process.env.PORT, process.env.IP, function(){


console.log("Server is listening!!!");
});
Views/posts.ejs
<h1>The Posts Page</h1>
<% for(var i = 0; i < posts.length; i++){ %>
<li> <%= posts[i].title %> - <strong><%= posts[i].author %></strong> </li>
<% } %>
<% posts.forEach(function(post){ %>
<li> <%= post.title %> - <strong><%= post.author %></strong> </li>
<% }) %>
Views/love.ejs:
<h1>You fell in love with: <%= thingVar.toUpperCase() %> </h1>
<% if(thingVar.toLowerCase() === "rusty"){ %>
<p>GOOD CHOICE! RUSTY IS THE BEST!</p>
<% } else { %>
<p>Bad choice! You should have said Rusty!</p>
<% } %>
Views/home.ejs:
<h1>This is the home page!</h1>
<img src="--------------- ">
----------------------------------------END-------------------------------------

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

APIs’ major features in Web Development


APIs can be used for mashups that is information from one site can be mixed with that of
another. Authentication is one of the important things to be noted as all APIs are not public. API
keys are required in case of authentication for safe use. For example, please refer to Gmail API
Authentication

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)

#### var request = require('request');


request('https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-
4.4203400&date=2020-03-21', function(error, response, body){
if(!error && response.statusCode == 200){
console.log(body);
}});
Output:
{"results":{"sunrise":"6:18:07 AM","sunset":"6:30:59 PM","solar_noon":"12:24:33
PM","day_length":"12:12:52","civil_twilight_begin":"5:52:22 AM","civil_twilight_end":"6:56:44
PM","nautical_twilight_begin":"5:22:08 AM","nautical_twilight_end":"7:26:58
PM","astronomical_twilight_begin":"4:51:27 AM","astronomical_twilight_end":"7:57:38
PM"},"status":"OK"}
###console.log(body[“results”]).output:undefined.Can’t acess this information inside of
codes .cause it’s not a javascript object.
So turn it into an object ,need to doing parse it.parse ->body.
Var parseddata=JSON.parse(body);
Console.log(parseddata);
Output: {
results: {
sunrise: '6:18:07 AM',
sunset: '6:30:59 PM',
solar_noon: '12:24:33 PM',
day_length: '12:12:52',
civil_twilight_begin: '5:52:22 AM',
civil_twilight_end: '6:56:44 PM',
nautical_twilight_begin: '5:22:08 AM',
nautical_twilight_end: '7:26:58 PM',
astronomical_twilight_begin: '4:51:27 AM',
astronomical_twilight_end: '7:57:38 PM'
},
status: 'OK'
}
Ex: console.log(parseddata["results"]["astronomical_twilight_end"]);
JSONPlaceholder is a free online REST API that you can use whenever you need some fake data.
The eval() function evaluates or executes an argument.If the argument is an
expression, eval() evaluates the expression. If the argument is one or more
JavaScript statements, eval() executes the statements.
1.eval() is a global function in JavaScript that evaluates a specified string as
JavaScript code and executes it.example:eval("alert('this is executed by
eval()')");
2.The eval() function can also call the function and get the result as shown
below.var result;function Sum(val1, val2){return val1 + val2;}eval("result =
Sum(5, 5);");alert(result);
3.eval can convert string to JSON object.var str =
'({"firstName":"Bill","lastName":"Gates"})';var obj =
eval(str);obj.firstName; // Bill
// it is slow, not secure, and makes code unreadable and maintainable.
#####eval(require(‘locus’))---→can manipulate the program at runtime.
var request = require('request');
request('https://jsonplaceholder.typicode.com/users/1', function(error, response, body){
if(!error && response.statusCode == 200){
eval(require('locus'));
var parseddata=JSON.parse(body);
console.log(parseddata["query"]["results"]["channel"]["astronomy"]["sunset"]);
}
});
Manipulating code:

ʆ: 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)

Mongoose:interact mongo database with mongoose


Install mongoose
####adding a new cat to the DB
Schema:::everything in mongoose starts with schema.each schema maps to a mongodb collection and defines
the shape of the documents within collection
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/cat_app");

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);

var mongoose = require("mongoose");


mongoose.connect("mongodb://localhost/yelpcampa",{ useNewUrlParser:true,useUnifiedTopology: true });
var Post = require("./models/post");
var User = require("./models/user");
/* User.create({
email: "bob@gmail.com",
name: "Bob Belcher"
});*/at first one user is created and then comment it and create a post.
Post.create({ title: "How to cook the best burger pt. 4", content: "AKLSJDLAKSJD"}, function(err, post){
User.findOne({email: "bob@gmail.com"}, function(err, foundUser){
if(err){console.log(err); }
else {
foundUser.posts.push(post);
foundUser.save(function(err,data){
if(err){
console.log(err);}
else{ console.log(data);}
}}); }});});
// {
posts: [
{ _id: 5e777aa56030bd1644eefa8a,title: 'How to cook the best burger pt. 4',content: 'AKLSJDLAKSJD', __v: 0
}],_id: 5e775e13c9b6552eacab8500,email: 'bob@gmail.com',name: 'Bob Belcher',__v: 1}
User.findOne({email: "bob@gmail.com"},function(err, user){
if(err){ console.log(err); }
else {console.log(user);} });
output::
{ posts: [ 5e777aa56030bd1644eefa8a, 5e777c5413b4a72c78bedbf5 ],
_id: 5e775e13c9b6552eacab8500,
email: 'bob@gmail.com',
name: 'Bob Belcher',
__v: 2}
User.findOne({email: "bob@gmail.com"}).populate("posts").exec(function(err, user){
if(err){console.log(err); } else {console.log(user); } });
//finding a user and populate the field posts(var userschema posts)those obj id’s,find correct data and then stick it
in the post array and run exec(start the query)
------------------------------------------------------------------------END------------------------------------------------------------------------
Yelpcamp::
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
Campground = require("./models/campground"),
Comment=require(“./models/comment”),
seedDB = require("./seeds")
mongoose.connect("mongodb://localhost/yel3",{ useNewUrlParser: true, useUnifiedTopology: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
seedDB();
app.get("/", function(req, res){ res.render("landing");});
//INDEX - show all campgrounds--
app.get("/campgrounds", function(req, res){// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){ console.log(err); } else {res.render("index",{campgrounds:allCampgrounds}); } });});
//CREATE - add new campground to DB
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; desc = req.body.description;
var newCampground = {name: name, image: image, description: desc} // Create a new campground
Campground.create(newCampground, function(err, newlyCreated){
if(err){ console.log(err);} else { res.redirect("/campgrounds"); }});});
//NEW - show form to create new campground
app.get("/campgrounds/new", function(req, res){ res.render("new.ejs"); });
// SHOW - shows more info about one campground
app.get("/campgrounds/:id", function(req, res){ //find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err){ console.log(err);} else { console.log(foundCampground)
res.render("show", {campground: foundCampground}); }});})
app.listen(3000, function(){console.log("The YelpCamp Server Has Started!");});
models/campground.js:
var mongoose = require("mongoose");
var campgroundSchema = new mongoose.Schema({
name: String, image: String, description: String,
comments: [ {type: mongoose.Schema.Types.ObjectId, ref: "Comment" } ]});
module.exports = mongoose.model("Campground", campgroundSchema);
models/comment.js:
var mongoose = require("mongoose");
var commentSchema = mongoose.Schema({ text: String, author: String});
module.exports = mongoose.model("Comment", commentSchema);
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">
<input class="form-control" type="text" name="description" placeholder="description"> </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 %
Views/index.ejs(campgrounds.ejs from previous code)
<div class="caption"> <h4><%= campground.name %></h4></div>
<p><a href="/campgrounds/<%= campground._id %>" class="btn btn-primary">More Info</a> </p>
Views/landing.ejs &views/new.ejs &views/partials/header.ejs &/footer.ejs is same as previous code
-------------------------------------------------------------END-----------------------------------------------------------------

var express = require("express"),


app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
Campground = require("./models/campground"),
Comment = require("./models/comment"),
seedDB = require("./seeds")
mongoose.connect("mongodb://localhost/yel3",{ useNewUrlParser: true, useUnifiedTopology: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
seedDB();
app.get("/", function(req, res){ res.render("landing");});
//INDEX - show all campgrounds
app.get("/campgrounds", function(req, res){// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){ console.log(err); }
else { res.render("campgrounds/index",{campgrounds:allCampgrounds});}});});
//CREATE - add new campground to DB
app.post("/campgrounds", function(req, res){ // get data from form and add to campgrounds array
var name = req.body.name, image = req.body.image,desc = req.body.description;
var newCampground = {name: name, image: image, description: desc}
Campground.create(newCampground, function(err, newlyCreated){
if(err){console.log(err); }
else {//redirect back to campgrounds page
res.redirect("/campgrounds");
}});});
//NEW - show form to create new campground
app.get("/campgrounds/new", function(req, res){ res.render("campgrounds/new"); });
// SHOW - shows more info about one campground
app.get("/campgrounds/:id", function(req, res){ //find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err){ console.log(err); }
else { console.log(foundCampground) //render show template with that campground
res.render("campgrounds/show", {campground: foundCampground});
} });});
//comment routes
app.get("/campgrounds/:id/comments/new", function(req, res){ // find campground by id
Campground.findById(req.params.id, function(err, campground){
if(err){console.log(err); }
else { res.render("comments/new", {campground: campground});
} })});
app.post("/campgrounds/:id/comments", 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 { campground.comments.push(comment);campground.save(); res.redirect('/campgrounds/'
+ campground._id);
}});}});});
app.listen(3000, function(){console.log("The YelpCamp Server Has Started!");});
Seeds.js:
var mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment = require("./models/comment");
var data = [
{ name: "Cloud's Rest", image: "https://farm4.staticflickr.com/3795/10131087094_c1c0a1c859.jpg",
description: "number1" },
{ name: "Desert Mesa", image: "https://farm6.staticflickr.com/5487/11519019346_f66401b6c1.jpg",
description: "number 2" },]
function seedDB(){
//Remove all campgrounds
Campground.remove({}, function(err){
if(err){ console.log(err);}
console.log("removed campgrounds!");
//add a few campgrounds
data.forEach(function(seed){
Campground.create(seed, function(err, campground){
if(err){console.log(err) }
else {console.log("added a campground");//create a comment
Comment.create(
{ text: "This place is great, but I wish there was internet", author: "Homer" }, function(err,
comment){
if(err){console.log(err);}
else { campground.comments.push(comment);campground.save();
console.log("Created new comment");
} });}});});}); }
module.exports = seedDB;
views/campgrounds/index.ejs:
views/campgrounds/new.ejs:
views/campgrounds/show.ejs:
<% include ../partials/header %>
<div class="container"><div class="row"><div class="col-md-3">
<p class="lead">YelpCamp</p>
<div class="list-group">
<li class="list-group-item active">Info 1</li><li class="list-group-item">Info 2</li> <li class="list-group-item">Info 3</li>
</div></div>
<div class="col-md-9"><div class="thumbnail">
<img class="img-responsive" src="<%= campground.image %>">
<div class="caption-full">
<h4 class="pull-right">$9.00/night</h4>
<h4><a><%=campground.name%></a></h4>
<p><%= campground.description %></p>
</div></div>
<div class="well"><div class="text-right">
<a class="btn btn-success" href="/campgrounds/<%= campground._id
%>/comments/new">Add New Comment</a>
</div> <hr>
<% campground.comments.forEach(function(comment){ %>
<div class="row"><div class="col-md-12">
<strong><%= comment.author %></strong>
<span class="pull-right">10 days ago</span>
<p>
<%= comment.text %> </p>
</div> </div><% }) %></div></div></div></div>
<% include ../partials/footer %>
Views/comments/new.ejs:
<% include ../partials/header %>
<div class="container">
<div class="row">
<h1 style="text-align: center">Add New Comment to <%= campground.name %></h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/campgrounds/<%= campground._id %>/comments" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="comment[text]" placeholder="text">
</div>
<div class="form-group">
<input class="form-control" type="text" name="comment[author]" placeholder="author">
</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 %>
models/campground.js &models/comment.js &partials/header and footer are same.
--------------------------------------------------------------END-----------------------------------------------------------------------
Passport:Passport uses the concept of strategies to authenticate requests.
Passport-local:Passport strategy for authenticating with a username and password.This module
lets you authenticate using a username and password in your Node.js application.
Passport-local-mongoose:Passport-Local Mongoose is a Mongoose plugin that
simplifies building username and password login with Passport.

Plugin Passport-Local Mongoose:


First need to plugin Passport-Local Mongoose into User schema.
User.plugin(passportLocalMongoose);Passport-Local Mongoose will add a username, hash and salt
field to store the username, the hashed password and the salt value.Additionally adds some
methods to Schema.
Configure Passport/Passport-Local
You should configure Passport/Passport-Local as described in the Passport Guide.
Passport-Local Mongoose supports this setup by implementing a LocalStrategy and
serializeUser/deserializeUser functions.
To setup Passport-Local Mongoose use this code:
// requires the model with Passport-Local Mongoose plugged in
const User = require('./models/user');
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Make sure that you have a mongoose connected to mongodb and you're done.
Express-session:create a session middleware with given option.session data is stored
server-side ,session-id is stored cookie itself.
Secret:Used to sign the session id cookie.Can be a string for a single secret or an array of
multiplesecrets.if an array of secrets is provided,only first element will be used to sign the session-id
cookie,while all the elements will be considered when verifying the signature in requests.

Saveuninitialized: Forces a session that is "uninitialized" to be saved to the store. A session


is uninitialized when it is new but not modified. Choosing false is useful for implementing login sessions,
reducing server storage usage, or complying with laws that require permission before setting a cookie.
Choosing false will also help with race conditions where a client makes multiple parallel requests without
a session.
Resave:Forces the session to be saved back to the session store, even if the session was never modified
during the request.
Important to understand session based auth and token based auth.
https://dev.to/thecodearcher/what-really-is-the-difference-between-session-and-token-based-
authentication-2o39
var express = require("express"),
mongoose = require("mongoose"),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./models/user"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose")
var app = express();
app.set('view engine', 'ejs');
mongoose.connect("mongodb://localhost/yel3",{ useNewUrlParser: true, useUnifiedTopology: true });
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "Rusty is the best and cutest dog in the world",
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());
// ROUTES
app.get("/", function(req, res){ res.render("home");});
app.get("/secret",isLoggedIn, function(req, res){res.render("secret"); });
// Auth Routes//show sign up form
app.get("/register", function(req, res){res.render("register"); });
//handling user sign up
app.post("/register", function(req, res){
User.register(new User({username: req.body.username}), req.body.password, function(err, user){
if(err){ console.log(err); return res.render('register');}
passport.authenticate("local")(req, res, function(){res.redirect("/secret");
});});});
// LOGIN ROUTES//render login form
app.get("/login", function(req, res){res.render("login"); });
//login logic//middleware
app.post("/login", passport.authenticate("local", {successRedirect: "/secret",failureRedirect: "/login"
}) ,function(req, res){
});

app.get("/logout", function(req, res){ req.logout();res.redirect("/");});


function isLoggedIn(req, res, next){ if(req.isAuthenticated()){return next();}res.redirect("/login");}
app.listen(3000, function(){ console.log("server started.......");})
models/user.js:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({username: String,password: String });
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Views/home.ejs:
<h1>This is the home page!</h1>
<li><a href="/register">Sign Up!</a></li><li><a href="/login">Login!</a></li><li><a href="/logout">Logout!</a></li>
Views/login.ejs:
<h1>Login</h1>
<form action="/login" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<button>Login</button>
</form>
<li><a href="/register">Sign Up!</a></li><li><a href="/login">Login!</a></li><li><a href="/logout">Logout!</a></li>
Views/register.ejs:
<h1>Sign Up Form</h1>
<form action="/register" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<button>Submit</button>
</form>
<li><a href="/register">Sign Up!</a></li><li><a href="/login">Login!</a></li><li><a href="/logout">Logout!</a></li>
Views/secret.ejs:
<h1>This is the secret page!</h1><p>You found me!</p>
<img src="https://scontent-sjc2-1.xx.fbcdn.net/hphotos-xaf1/v/t1.0-
9/197592_1007017930183_5279_n.jpg?oh=2e24b7a0b113730421ec4fc65ddad724&oe=568A3492">
<li><a href="/register">Sign Up!</a></li><li><a href="/login">Login!</a></li><li><a href="/logout">Logout!</a></li>
-------------------------------------------------------------------------------END------------------------------------------------------------------------
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
Campground = require("./models/campground"),
Comment = require("./models/comment"),
User = require("./models/user"),
seedDB = require("./seeds")

//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(function(req, res, next){


res.locals.currentUser = req.user;
next();
});

app.use("/", indexRoutes);
app.use("/campgrounds", campgroundRoutes);
app.use("/campgrounds/:id/comments", commentRoutes);

app.listen(process.env.PORT, process.env.IP, function(){


console.log("The YelpCamp Server Has Started!");
});
routes/camogrounds.js: var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");

//INDEX - show all campgrounds


router.get("/", function(req, res){
// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){
console.log(err);
} else {
res.render("campgrounds/index",{campgrounds:allCampgrounds});
}
});
});

//CREATE - add new campground to DB


router.post("/", middleware.isLoggedIn, function(req, res){
// get data from form and add to campgrounds array
var name = req.body.name;
var image = req.body.image;
var desc = req.body.description;
var author = {
id: req.user._id,
username: req.user.username
}
var newCampground = {name: name, image: image, description: desc, author:author}
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to campgrounds page
console.log(newlyCreated);
res.redirect("/campgrounds");
}
});
});

//NEW - show form to create new campground


router.get("/new", middleware.isLoggedIn, function(req, res){
res.render("campgrounds/new");
});

// SHOW - shows more info about one campground


router.get("/:id", function(req, res){
//find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err){
console.log(err);
} else {
console.log(foundCampground)
//render show template with that campground
res.render("campgrounds/show", {campground: foundCampground});
}
});
});

// EDIT CAMPGROUND ROUTE


router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
res.render("campgrounds/edit", {campground: foundCampground});
});
});

// UPDATE CAMPGROUND ROUTE


router.put("/:id",middleware.checkCampgroundOwnership, function(req, res){
// find and update the correct campground
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err,
updatedCampground){
if(err){
res.redirect("/campgrounds");
} else {
//redirect somewhere(show page)
res.redirect("/campgrounds/" + req.params.id);
}
});
});

// DESTROY CAMPGROUND ROUTE


router.delete("/:id",middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds");
}
});
});

module.exports = router;
routes/comments.js:

var express = require("express");


var router = express.Router({mergeParams: true});
var Campground = require("../models/campground");
var Comment = require("../models/comment");
var middleware = require("../middleware");

//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);
}
});
}
});
});

// COMMENT EDIT ROUTE


router.get("/:comment_id/edit", middleware.checkCommentOwnership, function(req, res){
Comment.findById(req.params.comment_id, function(err, foundComment){
if(err){
res.redirect("back");
} else {
res.render("comments/edit", {campground_id: req.params.id, comment: foundComment});
}
});
});
// COMMENT UPDATE
router.put("/:comment_id", middleware.checkCommentOwnership, function(req, res){
Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err,
updatedComment){
if(err){
res.redirect("back");
} else {
res.redirect("/campgrounds/" + req.params.id );
}
});
});

// COMMENT DESTROY ROUTE


router.delete("/:comment_id", middleware.checkCommentOwnership, function(req, res){
//findByIdAndRemove
Comment.findByIdAndRemove(req.params.comment_id, function(err){
if(err){
res.redirect("back");
} else {
res.redirect("/campgrounds/" + req.params.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");
});

// show register form


router.get("/register", function(req, res){
res.render("register");
});

//handle sign up logic


router.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if(err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/campgrounds");
});
});
});

//show login form


router.get("/login", function(req, res){
res.render("login");
});

//handling login logic


router.post("/login", passport.authenticate("local",
{
successRedirect: "/campgrounds",
failureRedirect: "/login"
}), function(req, res){
});

// 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");

var campgroundSchema = new mongoose.Schema({


name: String,
image: String,
description: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});

module.exports = mongoose.model("Campground", campgroundSchema);


var mongoose = require("mongoose");

var commentSchema = mongoose.Schema({


text: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});

module.exports = mongoose.model("Comment", commentSchema);


models/user.js:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({


username: String,
password: String
});

UserSchema.plugin(passportLocalMongoose)

module.exports = mongoose.model("User", UserSchema);


middleware/index.js: var Campground = require("../models/campground");
var Comment = require("../models/comment");

// all the middleare goes here


var middlewareObj = {};

middlewareObj.checkCampgroundOwnership = function(req, res, next) {


if(req.isAuthenticated()){
Campground.findById(req.params.id, function(err, foundCampground){
if(err){
res.redirect("back");
} else {
// does user own the campground?
if(foundCampground.author.id.equals(req.user._id)) {
next();
} else {
res.redirect("back");
}
}
});
} else {
res.redirect("back");
}
}

middlewareObj.checkCommentOwnership = function(req, res, next) {


if(req.isAuthenticated()){
Comment.findById(req.params.comment_id, function(err, foundComment){
if(err){
res.redirect("back");
} else {
// does user own the comment?
if(foundComment.author.id.equals(req.user._id)) {
next();
} else {
res.redirect("back");
}
}
});
} else {
res.redirect("back");
}
}

middlewareObj.isLoggedIn = function(req, res, next){


if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}

module.exports = middlewareObj;
public/stylesheets/main.css: .thumbnail img {
width: 100%;
}

.thumbnail {
padding: 0;
}
.thumbnail .caption-full {
padding: 9px;
}

#delete-form {
display: inline;
}

S-ar putea să vă placă și