0% found this document useful (0 votes)
30 views

Back End

Uploaded by

Debasis Baraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Back End

Uploaded by

Debasis Baraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

Back end bd class 1

N2EHRu8L1eNUMaO2 password 6aSdtIl6UWtlEX00

express js ke dwara server create hota


it is used to create sever side application

npm init -y after going insided the folder in terminal use this command

npm i express install experess

const express=require('express') instance of express

and kept the name

const app=express()

app.listen(3000, ()=>{})

it start listinig on port number 3000

create route
get -this takes two paramrter path and callback
call back -A function with parameters (req, res). This middleware function defines
how the server should respond to the request.
app.get('/',(req,res)=>{

res.send("hello");

})

app.post('/',(req,res)=>{
const {name ,brand}=req.body//ismai name and brand pada goga is req ke body mai

res.send("hello");

})

The reason you are not able to get data from the req.body in your POST request
could be due to the absence of middleware to parse the incoming request body

middelware -bodyparser
ye request ko parse karta hai body mai jo data pass hua hai

const bodyParser =require('body-parser');


app.use(bodyParser.Json())
MongoDb -----No sql Database
data stored in the form of doc and key value pair and grpahs etc

to connect mongo db and express js use mongoose(it is odm(object data model


library)

node js data treated as object and in mongo db data treated as document

const mongoose= require(mongoose')


mongoose.connect('mongodb://localhot:27017/myDatabase', {useNewurlparser:true,
useUnifiedtopology:true}).then(()=>{console.log("connection Succesfull")})
.catch(()=>{})
it is a promise

-----------------------------------------------------------------------------------
--------
file strutre

index.js mai put routes then the routes should some work like business logic so
then put that route logic in controller(yeaha opertaions hota )

models-- to define a schema of database or custome database

Schema Definition: Define the structure of your MongoDB documents.


Data Validation: Ensure data integrity with required fields and constraints.
Database Operations: Use models for CRUD operations with MongoDB.

1- config folder -in this folder we configure the connection node js and Mongoose
database

const mongoose = require("mongoose");


instance of monggose
mongoose.connect('mongodb://localhot:27017/myDatabase', {useNewurlparser:true,
useUnifiedtopology:true}).then(()=>{console.log("connection Succesfull")})
.catch(()=>{})
it is a promise

crete a fun to establish the connection


between app and database

1 st parameter url 2nd take some flags


process wale object me database url feed kar na hai to use .env library

--instal that npm i dotenv


dotenv is used to manage environment variables in a Node.js project. It loads
variables from a .env file into process.env, allowing sensitive data (like API
keys, database URIs, and secret keys) to remain secure and separate from the code.

require("dotenv").config();// this line


will do jo v env mai define kiya hoga wo "process" object mai load hojyega
mongoose.connect(process.env.DATABASE_URL,{
useNewurlParsere:true,
useUnifiedTopology:true,
})

The process.exit(code) method in Node.js is used to terminate the current Node.js


process. It can take an optional exit code as an argument, which is a number that
indicates the exit status of the process.

module.exports=dbConnect //backend sysntax for import

model define

const mongoose=require('mongoose')
const todoSchema =new mongoose.Schema({

title:{
type:String,
required:true,
maxLength:10,

},
//like this you can write more object

})

module.exports =mongoose.model("Todo",todoSchema) //koi v use kar na cha hae to kar


sskta hai Todo ke naaam se

//how to import in back end

const Todo= require("../models/Todo")


//define route handler

exports.createTodo= async(req,res)=>{
const {titel ,description}=req.body
const response =awiat Todo.create({title,description}

res.status(200).json({

data:response;

})

//to create route

//fetch the contrller then map in route


const router = express.Router();
// import controller
const {creteTodo}= require(../controller/creterTodo);

define api route

route.post("/creteTodo" ,creteTodo)//"/creteTodo" is path pe jaoge to creteTodo ye


controller mai mapperd hgya

modulw.exports=route

//middleware to pasrse json req body

app.use(express.json())

//import routes for totdo api routes


//const todoRoutes =require('../routes/todos')

app.use ("/api/v1", todoRoutes);

req.params.id to get id form data base

req.params.id: Use when the ID is part of the URL path (like /users/:id).
req.body.id: Use when the ID is part of the request body (usually with POST, PUT,
PATCH).

post:{
type:mongoose.Schema.Types.ObjectId , //object id of post type
ref: "Post",// refrence to the post model
},

chat gpt

another way to puch data in data abase apart for create

exports.createComment=async(req,res)=>{
try{
//fetch data fro req body

const {post, user,body}=req.body


//crete a commnet object

const comment =new Comment({


post,user,body
});

//save the new commet into data base

const savedComment=await comment.save();

}
catch(error){
}

//find the post by id add the new commnet to its comment array

const updatedPost = await Post.findByIdUpdate(post,{$push:


{comments:savedComment._id}},{new:true},)

new true mean -jab ye sara kaam hojye jo upara likha hai tab jo updated doc hoga
wo return kar na

Class -5

what is express-->backednd frmae work

steps for project

crete folder app


open terminal go to floder app
npm init -y
open it in vs code
interminal install express
npm install express
require function is used to import somthing

const express=require('express')
const app=express()/application is created not live but created

middle ware--->before sending resposnse if you want to do somthing then middle ware
is used

next use to call next middleware

-----------------------------------------------------------------------------------
-------------------------------------------------------
AURTH N And AUTH Z Class 1

Authentication -->identity verification


Authorization: Determining what the user is allowed to do (access control).

req.header("Authorization").replace("Bearer","") this is most secure

req ke header mai se authorization key se value le au aur jaha bearre ko empty
string se repalce kar do

req.cookies.token||

req.body.token||

FILE UPLOAD CALSS

You might also like