Full Post Page
 

Nodejs template engines with Express part-2

Category: NODE JS & Written by Admin On May-01-2025 14:33:04

EXPRESSJS EJS Template official webiste ejs.co Embedded javaScript Templating-> EJS Template -> Template engine Based on javaScript EJS provides a clean and convenient way to create view in expessjs BENEFITS:create Dynamic and Reuable Template Ejs Template Tag syntax TAG description <% %> controll flow, no output <% = %> Output escaped value (safe) <% - % > Output unescaped value(unsafe) <% # %> comment not showing output <%-%> Remove the folling newline <%_%> remove white space before IT <%_%> remove all white space after IT benifit Prevents(save) for XSS attacks Example <ul> <% for(let i=1;i<=3;i++){%> <li> item <% = i %> <li> <% } %> </ul> create new project npm install -y npm install express nodemon ejs note fist nodejs,exprss nodemon for contine server run and ejs template engine GO package.json file scripting run developing "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start":"nodemon index.js" }, if you want to javaScript ES6 then Go package.json after"main": "index.js", write "type":"module", THAN create index.js file and write inclue const expess =require('expess') or ES6 import express from 'express'; RUN npm run start variable value print res.render("about" ,{title:'About page',message:'wekcome to EJS'}) <title> <%= title %> </title> javaScript control print loop ,condition <% if(message){%> <p><%= message %> </p> <%}else{ %> <span>Ther is no message</span> <% } %> loop <% let items = ["apple","Banana","orange","Cherry"] %> <ul> <% items.forEach( item => { %> <li> <%= item %> </li> <% }) %> </ul> // indexing array // array object app.get('/about',(req,res)=>{ var users=[ {name:'hotdr kumar',age:45,city:'mumbai'}, {name:'akshsy kumar',age:34,city:'patna'}, {name:'tsrd kumar',age:65,city:'ghar'}, {name:'tsmrd kumar',age:54,city:'hforla'}, ]; res.render("about",{ title:"Home page", message:"welcome", items:users }) }) //view template <table border="1" width="500px"> <% items.forEach( item => { %> <tr> <td> <%= item.name _%></td> <td> <%= item.age _%></td> <td> <%= item.city _%></td> </tr> <% }) %> </table> EJS Template From Submission Partials Serving Static Files(css,js,Images) app.use(express.urlencoded('extended:false')) // use for form submited in index page app.get('/form',(req,res)=>{ res.render('form') }) app.post('/submit',(req,res)=>{ const name=req.body.myname const message=`Hello,${name} You submitted the form` res.send(message) }) EJS TEMPLATE :Partials header,menu,sidebar reusbility method <%- include ('header')-%> method <%- include ('footer')-%> app.use(express.static('public')) // use for css index.js NODEJS MONGODB CRUD create new project folder opne vs code CMD NPM INSTAL -Y ,npm install express nodemon ejs CREATE INDEX.JS SET YOUR package.JSON FILE scripts "START":nodemon index.js Go index.js page // include your express js here //start your server // include your express js const express=require('express') const app=express() //start your server app.listen(3000,()=>{ console.log("server started Successfully pn poart 3000.") }) make route app.get('/',(req,res)=>{}) //add middleware app.set('view engine',"ejs") app.use(express.urlencoded({extended:false})) app.use(exprss.static('public')) set css path create all assets and css in public <link href="/custom.css" rel="stylesheet"> set your partials <%- include ('partials/header.ejs') %> @After Setup HTML template in ExpressJs @Learn to read data form MongoDB ExpressJS with MongoDB mongoose =====>coneection | DATABASE (MongoDB) expressJs =======>Run query step 1. npm install mongoose step 2. const mongoose=require('mongoose') step 3. mongoose.connect('mongodb://127.0.0.1:27017/databse-name') step 4. const test=mongoose.model('User',mongoose.Schema({ name:{ type:String }, age:{ type:Number } } )); NB: mongodb datatype: String,Number,Date,Buffer,Boolean,Mixed,ObjectId,Array,Decimal,Map,UUID,Double,Int32,Int64 MONGODB CRUD query syntax CREATE: insertOne(), insertMany READ: find(), findOne() UPDATE: updateOne(), updateMany() Delete: deletOne(), deleteMany() Extra short mongodb command create() findById() findByIdAndUpdate() findByIdAndDelete() website:mongoosejs.com install mongodb in your nodejs project npm install mongoose include mongoose package in your index.js const mongoose =require("mongoose) //database CONNECTION Go CMD type mongosh and copy CONNECTION to url and paste in connection db mongoose.connect(' mongodb://127.0.0.1:27017/contacts-crud') .then(()=>console.log("database conneted.")) checck connection cmd mongosh show dbs, use database_name, show collections insert data here db.collections_name.inser({filed_name:"value"}) db.contacts.insertOne({ first_name:"ramesh", last_name:"jha", email:"ramesh@aika.com", phone:848995487954, address:"#54,AG Road,lp" }) showing db.contacts.find() Go Your Home route for showing dynamic data MVC (MODEL VIEW CONTROLLER) BIFINT:SEPARATION OF CONCERNS , CODE ORGANIZATION ,ESAY TO FIND Error,independent Block, Reduces the complexity of web appliction,ESAY to midify,code reusbility,improved collaboration platform independent (use any PATTERN) MODEL->CODE OF DATABASE RELATED(COLLECTION SCHEMA) VIEW ->HTML CODE USING EJS CONTROLLER->BUSINESS LOGIC (CODING LOGIC) CONTROLLER WORK AS A MEDIATOR BETWEEN MODEL AND VIEW MVC PATTERN WORK flow CONTROLLER-------REQUESST---->MODEL SEND DATA/| | | | | VIEW | <-------RESPONE------------MODEL | | RES | REQUEST routes | | | | USER WWW.ABC.COM .env Files ( by default install rhta hai na rhe to command npm install dotenv) A .env(enviroment) file is used to store configuration variablees like .Database connection strings .API key .PORT numbers .Sensitive credemtioals (without hardcoding them in the code) Benefits: security- keeps credentials hidden from your codebase .Portability-Easy to change values without moddifing code .better managemnet-store configuration in single Files CRUD BASIC ERROR HANDING method 1 method 2 try{ app.use((req,res,next)=>{}); (THIS VALID ID OR NOT) }catch{} trY(FOR DATA validat AVLIABLE IN DATABASE OR NOT) Examble 1. var paramId=mongoose.Types.ObjectId.isValid(req.params.id) if(!paramId){ res.render('404',{message:"Invalid Id"}) Example 2. try{ const contactfet=await Contact.findById(req.params.id) if(!contactfet) return res.render('404',{ message:"contact not found"}) res.render('show-contact',{contactfet: contactfet}) }catch(error){ res.render('500',{message:error}) // if coding error yhan shoe } } => Express js pagination package step 1.: npm install mongoose-paginate-v-2(need add plugin) step 2.(where is define Schema) :import mongoosePaginate from 'mongoose-paginate-v2' step 3.: const useSchema=new mongoose.Schema({ name:String, email:String }); userSchema.plugin(mongoose.paginate-v2); const user = mongoose.model('User',userSchema); export default user; step 4. User.paginate({},{page:1,limit:3}) url http://LOCALHOST:3000/?page=2 NOTES better standarding VISIT npmjs.com=>find mongoose-paginate =>copy mongoose-paginate-v-2 or what you want to copy and check properly how to use command npm i mongoose-paginate-v2 >>> then Go Your Schema model file import mongoosePaginateRUPESH from "mongoosepackage_name what are you using" import mongoosePaginateRUPESH from "mongoose-paginate-v2" Schemavariable_name.plugin(mongoosePaginateRUPESH) // add below schema page

Comments

Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29