instagram clone app - by youtube


            MERN STACK TUTORIAL MAKING AN INSTAGRAM APPLICATION CLONE APP

     


note:

1. use of return:  if i dont want to go proceed further then definately i willl be use the return before the line 

2.fineOne()- query in the database

youtube Link:                                           

https://www.youtube.com/watchv=-56IzWZufZU&list=PLB97yPrFwo5g0FQr4rqImKa55F_aPiQWk&index=10

blogger link:

https://www.blogger.com/u/1/blog/post/edit/4759790771070919523/6252291096120516278

mongodb account:

dwijendratech@gmail.com


                                    ....................................................................................................



   chapter 01: hello world program 


step 01:  create the server folder

step 02: type npm init to initialize our server   :::::   By this command package.json is created 

step 03: open server in vs code

step 04:  will install express.js  ::::::::::   npm install express

step 05: make app.js 

step 06: require express 

step 07: invoke express

step 08: make a get request with req and res   - app.get

step 09: listen on specific port ::  by example port 5000 

step 10: make a listen request   - app.listen

step 11:  type at terminal and check -   node app - it will show  at which server we are working - server name  = isse server run ho jayega browser par jab bhi aap localhost type karoge at the browser

step 12: type localhost:5000 at the terminal   - 

step 13: now change in the route - app.get from / to /home 


                                                      chapter 02: Custom Middleware

step01: create a middleware

step02: pass this middleware by using the use command  app.use 

What is middleware:

middleware is a code   which takes the incoming request and it modifies it before it reaches to actual route handler 

for example user will be making a get request to this show now before user make the request to the slash route this middleware will come in between and it will modify the request 

note: now after middleware executed server will hanging  - why this server is hanging we will see

step 03:  we will execute the code further with the next statement and run the code further as server will not hang now.

step 04: through nodemon auomatically restart our server when we will change our code files 

will install nodemon for this through this command ::   npm install nodemon -g

note: -g type karne se globally install ho jayega nodemon in your computer then you can use nodemon in your every project 

step 05: define middleware with next req and res 


                                              chapter 03: Setting up mongodb in atlas

step 01:  sign up to the cloud.mongodb.com account

step 02: create new project and give its name

step03: create a cluster with free

step04: in Network Access add IP Address -allow access from anywhere generally for that u can do anything 

step05: in database access create a new database user - name and password  - we can add user 

step6: 

create file keys.js 

in this in module.export paste below copy command and in password section paste the password of add user 

go to clusters and click on the connect - connecting the application- click to copy to the connection string copy 

step7: 

npm install mongoose 

require mongoose in app.js

connect mongoose in app.js

make usenewurlparser and usenewunifiedtopogy is true 


                                              chapter 04: Creating User Schema


schema is a blueprint that will tell the mongodb that we have this kind of data

step01: make model folder and inside this user.js file create

step02: 

const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name:{
type:String,
required:true
},
email:{
type:String,
required:true
},
password:{
type:String,
required:true
}
})

module.exports=mongoose.model("User",userSchema)

step03; in app.js

require('./models/user')

step 04: in app.js

mongoose.model("User")




                                             chapter 05: Getting data in request body 


                                       

step 01: create a seperate folder named routes  in that create the seperate file auth.js

step 02: In app.js require this models/user

step 03: in app.js use the auth file with command app.use - by this command we can register our routes

step 04: start working on sign up routes

A  post request of posting name email and password- we have made this 

we can not test this in browser so we need this service postman to test and check the api

how to check it at the postman

for signup api-

post signup 

in headers - content type is application.json

in body - we can select here raw - 

name:mukesh

send data through postman - this will throw an error 

now name is undefined so request dont send the request 

so we should tell our express  server does not automatically pass the request to json so we need to tell our server to pass the request

                                                     app.use(express.json())

This is the middleware that we are making inside app.use because we want to take the incoming request that will pass to the json before it reach us to the actual route handler 

save it and again restart it and send the request through the postman 

again an error-

now we will go the the auth.js and in router.post make it req.body through the req.body.name

restart the server then and make a request through the postman-

now this will hang and at the terminal it will show us undefined

i have done the mistake 

i have put this line before the route and i will do it after the route 

before 

app.use(require('./routes/auth'))
app.use(express.json())


after

app.use(express.json())
app.use(require('./routes/auth'))


now again the postman is hanged but the server will show the name mukesh

so we can access the data from front end we are sending in req.body in auth.js

and now i will destructure this in name email and body

before 

console.log(req.body)


after 

router.post('/signup',(req,res)=>{
const {name,email,password} = req.body
if(!email || !password || !name){
res.json({error:"please add all the fields"})
}
})


then

router.post('/signup',(req,res)=>{
const {name,email,password} = req.body
if(!email || !password || !name){
res.json({error:"please add all the fields"})
}
res.json({message:"successfully posted"})
})


now we will be passing name email and password through postman in the body

and get message

{
"message": "successfully posted"

}                                                 


after this

 router.post('/signup',(req,res)=>{

const {name,email,password} = req.body
if(!email || !password || !name){
res.status(422).json({error:"please add all the fields"})
}
res.json({message:"successfully posted"})

})                                


now 

router.post('/signup',(req,res)=>{
const {name,email,password} = req.body
if(!email || !password || !name){
return res.status(422).json({error:"please add all the fields"})
}
res.json({message:"successfully posted"})
})


 we do not want to proceed further so i will add return before res.status



                                   Chapter 06:Saving or Posting data in MongoDatabase

note: we can see the users in the mongodbwebsite-clusters-connect

For This first we will work in auth.js

we will posting our data to mongodabase so how we will do this

at first we will require mongoose-

const mongoose= require(mongoose)

Second we will be making use of user model

const User = mongoose.model("User")

Note: the name should be same in auth.js and user.js 

in user.js this "User " name 

module.exports=mongoose.model("User",userSchema)

and 

in auth.js this  "User" name 

const User = mongoose.model("User")


Now in auth.js

we can use this User model and     we will use the method find one with this user model

add this code now 

User.findOne({email:email})
.then((savedUser)=>{
if(savedUser){
return res.status(422).json({error:"user already exists with that email"})
}
})
})


else we can save the data to the database  so now make changes in the code by make a new user and user.save 

User.findOne({email:email})
.then((savedUser)=>{
if(savedUser){
return res.status(422).json({error:"user already exists with that email"})
}
const user = new User({
email,
password,
name
})
user.save()
})
})

then add the catch methods:


.then((savedUser)=>{
if(savedUser){
return res.status(422).json({error:"user already exists with that email"})
}
const user = new User({
email,
password,
name
})
user.save()
.then(user=>{
res.json({message:'saved successfully'})
})
.catch(err=>{
console.log(err)
})
})
.catch(err=>{
console.log(err)
})
})



now after his code again showing post data successfully in the postman but in my case this is the error


MongooseError: Operation `users.findOne()` buffering timed out after 10000ms

    at Timeout.<anonymous> (/home/dwijendra/Desktop/mern-instagram-clone01/server/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)


                               Chapter 07:Saving or Posting data in MongoDatabase

bcrypt is used for the password encryption as the user is shown at mongodb website 

step01: npm install bcryptjs

step02: require this in auth.js

const bcrypt = require('bcryptjs')

step03; bcrypt the password

    bcrypt.hash(password,12)

we have given the number 12 here . the bigger the number the password is more secure


note: we can see the users in the mongodb website with the hashed password which we have created at the console


nnote : we used the catch block for any error



                                   Chapter 09:Sending Token sing JWT

if the user is sucessfully signed in then we will give it a token that is json web token

why i want to give use a token - because when user is signed in then user should be able to access the protective resources

step01: npm install jsonwebtoken

step02: create a secret key to generate the web token 

in keys.js -

JWT_SECRET:"efgdkgdgkdfgdnb"

type any random word by your side in this 

step03: 


                                 Chapter 10:Creating Middleware to Verify Token


step 01: In auth.js

router.get('/protected',(req,res)=>{
res.send("hello user")
})

step02: create a folder named middleware and create a file inside requireLogin

step03: write in auth.js

module.exports=(req,res,next)=>{

this above is the middleware function

step04: write this complete in this- 

const jwt = require('jsonwebtoken')
const {JWT_SECRET} = require('../keys')


module.exports=(req,res,next)=>{
const {authorization} = req.headers
//authorization === Bearer raafdkfkjkgke
if(!authorization){
return res.status(401).json({error:"you must be logged in"})
}
const token= authorization.replace("Bearer","")
jwt.verify(token,JWT_SECRET,(err,payload)=>{
if(err){
res.status(401).json({error:"you must be logged in "})
}

})
}



in requireLogin.js


const jwt = require('jsonwebtoken')
const {JWT_SECRET} = require('../keys')
const mongoose = require('mongoose')
const User = mongoose.model("User")

module.exports=(req,res,next)=>{
const {authorization} = req.headers
//authorization === Bearer raafdkfkjkgke
if(!authorization){
return res.status(401).json({error:"you must be logged in"})
}
const token= authorization.replace("Bearer","")
jwt.verify(token,JWT_SECRET,(err,payload)=>{
if(err){
return res.status(401).json({error:"you must be logged in "})
}

const {_id} = payload
User.findById(_id).then(userdata=>{
req.user = userdata
})
next()
})
}
Note: very important:
in postman youtuber write Bearer Token and we will give directly token then we
will find the value



                                              Chapter 11:Post Schema and Create Post Route 


Step01:
in app.js

add this after mongoose.connection.on


require('./models/user')

app.use(express.json())
app.use(require('./routes/auth'))



Step02: In model folder add post.js
















Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5