Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorial

  • 2022-01-04Collection date
  • 2022-02-15Updated
Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorial
  • Website address:webslesson.info
  • Server IP:216.239.32.21
  • Site description:

domain name:webslesson.infoValuation

about 500~20000

domain name:webslesson.infoflow

80

domain name:webslesson.infoGood or bad

Empty effort. in vain fierce

website:Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter TutorialWeights

2

website:Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter TutorialIP

216.239.32.21

website:Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorialcontent

(adsbygoogle=window.adsbygoogle||[]).push({google_ad_client:"ca-pub-",enable_pe_level_ads:true});(adsbygoogle=window.adsbygoogle||[]).push({google_ad_client:"ca-pub-",enable_pe_level_ads:true});Webslesson|PHP,MySql,Jquery,AngularJS,Ajax,CodeigniterTutorialWebslesson//s.length&&r("jQuery.fn.attr(props,pass)isdeprecated"),t&&!d.test(g)&&(o?aino:e.isFunction(e.fn[a])))?e(t)[a](i):("type"===a&&i!==n&&l.test(t.nodeName)&&t.parentNode&&r("Can'tchangethe'type'ofaninputorbuttoninIE6/7/8"),!e.attrHooks[c]&&p.test(c)&&(e.attrHooks[c]={get:function(t,r){vara,i=e.prop(t,r);returni===!0||"boolean"!=typeofi&&(a=t.getAttributeNode(r))&&a.nodeValue!==!1?r.toLowerCase():n},set:function(t,n,r){vara;returnn===!1?e.removeAttr(t,r):(a=e.propFix[r]||r,aint&&(t[a]=!0),t.setAttribute(r,r.toLowerCase())),r}},f.test(c)&&r("jQuery.fn.attr('"+c+"')mayusepropertyinsteadofattribute")),s.call(e,t,a,i))},e.attrHooks.value={get:function(e,t){varn=(e.nodeName||"").toLowerCase();return"button"===n?u.apply(this,arguments):("input"!==n&&"option"!==n&&r("jQuery.fn.attr('value')nolongergetsproperties"),tine?e.value:null)},set:function(e,t){vara=(e.nodeName||"").toLowerCase();return"button"===a?c.apply(this,arguments):("input"!==a&&"option"!==a&&r("jQuery.fn.attr('value',val)nolongersetsproperties"),e.value=t,n)}};varg,h,v=e.fn.init,m=e.parseJSON,y=/^([^]*)$/;e.fn.init=function(t,n,a){vari;returnt&&"string"==typeoft&&!e.isPlainObject(n)&&(i=y.exec(e.trim(t)))&&i[0]&&("")!=-1){ s[i]=s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx=s.join(""); } chop=(chop=1){ imgt=''; summ=summary_img; } varsummary=imgt+''+removeHtmlT(div.innerHTML,summ)+''; div.innerHTML=summary;}//]]>(function(d,s,id){varjs,fjs=d.getElementsByTName(s)[0];if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.8";fjs.parentNode.insertBefore(js,fjs);}(document,'script','facebook-jssdk'));WebslessonPHP,Node.js,React.js,MySql,Jquery,AngularJS,Ajax,Codeigniter,LarelTutorialMenuHomePHPMySqlJQueryAjaxLarelCodeigniterToolsOnlineSlugGeneratorOnlineSourceCodeFormatterHTMLEncoder/DecoderConvertCase&CountCharacterFreePHPProjectDemosAboutUsAboutUsWriteforUsPrivacyPolicyTermsandConditionContactMeFriday8March2024NodejsDr&DropMultipleFileUploadusingMulter Webslesson    01:18    CSS,dr&amp;drop,dranddrop,dranddropfiles,dranddropmultiplefile,drndrop,express,fileupload,fileuploadinnodejs,files,html,Jascript,multer,multiplefileupload,node.js    Nocomments   Introduction:Intoday'sdigitalworld,fileuploadingisacommonfunctionalityforwebapplications.Node.js,withitsasynchronousandevent-drivenarchitecture,offersanexcellentplatformforhandlingfileuploadsefficiently.Multer,amiddlewareforExpress.js,simplifiestheprocessofhandlingmultipart/form-data,makingitperfectforhandlingmultiplefileuploads.Inthistutorial,wewillexplorehowtoimplementdranddropmultiplefileuploadsusingNode.jsandMulter,ensuringthecontentisoptimizedforsearchengines.TableofContents:SettinguptheProjectEnvironmentInstallingDependenciesConfiguringMulterMiddlewareCreatingtheFrontendInterfaceImplementingDrandDropFunctionalityHandlingFileUploadsontheServerRunApplicationConclusion1.SettinguptheProjectEnvironment:Beforedivingintothecode,let'sensureweheNode.jsinstalledonoursystem.Ifnot,downloadandinstallitfromtheofficialNode.jswebsite. mkdirdr-drop cddr-drop 2.InstallingDependencies:InitializeanewNode.jsprojectandinstalltherequireddependenciesusingnpm: npminit-y npminstallexpressmulter 3.ConfiguringMulterMiddleware:CreateanExpress.jsserverunderserver.jsandconfigureMultermiddlewaretohandlefileuploads:server.js constexpress=require('express'); constmulter=require('multer'); constpath=require('path'); constapp=express(); constPORT=3000; app.use(express.static(__dirname)); //SetupMulterstore conststore=multer.diskStore({ destination:function(request,file,callback){ callback(null,'uploads/'); }, Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorialfilename:function(request,file,callback){ callback(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname)); } }); //InitializeMulterupload constupload=multer({store:store}); app.get('/upload',async(request,response)=>{ response.sendFile(__dirname+'/upload.html'); }); app.listen(PORT,()=>{ console.log(`Serverisrunningonport${PORT}`); }); 4.CreatingtheFrontendInterface:DesignasimpleHTMLpewithnameupload.htmlfilewithdranddropfunctionalityforuploadingfiles:upload.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>DrandDropFileUpload</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5"><b>DrandDropFileUploadinNode.js</b></h1> <divid="drop_zone"> <p>Dranddropfileshere</p> </div> <br/> <divclass="cardmb-5"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">UploadedFile</div> <divclass="colcol-6"></div> </div> </div> <divid="uploadedIme"class="card-body"> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <style> #drop_zone{ width:100%; min-height:200px; border:2pxdashed#ccc; border-radius:10px; padding:20px; box-sizing:border-box; display:flex; justify-content:center; align-items:center; flex-direction:column; } #drop_zone.hover{ background-color:#f0f0f0; } </style> 5.ImplementingDrandDropFunctionality:WriteJaScriptcodeinuplode.htmlfiletohandledranddropfunctionality:upload.html <script> vardropZone=document.getElementById('drop_zone'); dropZone.addEventListener('drover',(event)=>{ event.preventDefault(); dropZone.classList.add('hover'); }); dropZone.addEventListener('drlee',(event)=>{ event.preventDefault(); dropZone.classList.remove('hover'); }); dropZone.addEventListener('drop',(event)=>{ event.preventDefault(); dropZone.classList.remove('hover'); varfiles=event.dataTransfer.files; handlesFiles(files); }); functionhandlesFiles(files){ for(varcount=0;count<files.length;count++){ varfile=files[count]; uploadFile(file); } } functionuploadFile(file){ varformData=newFormData(); formData.append('file',file); fetch('/upload',{ method:'POST', body:formData }) .then(response=>response.json()) .then(data=>{ constgallery=document.getElementById('uploadedIme'); lethtml=`<imgsrc="/uploads/${data.filename}"class="img-thumbnail"/>`; gallery.innerHTML=gallery.innerHTML+html; }); } </script> 6.HandlingFileUploadsontheServer:Nowinserver.js,wehetohandlefileuploadsontheserver-sideusingExpress.js:server.js app.post('/upload',upload.single('file'),(request,response)=>{ response.json({filename:request.file.filename}); }); 7.RunApplicationAfterwritingallabovecode,forrunthisnodeapplicationinbrowser,wehetostartnodeserver,sowehegoestoterminalwindow,andtherewehetorunnodeserver.jscommandwhichwillstartnodedevelopmentserver.Andatbrowser,wehetoopenhttplocalhost:3000url,thenitwillopenthisNodeDrandDropapplicationinbrowser.8.Conclusion:Congratulations!You'vesuccessfullyimplementeddranddropmultiplefileuploadsusingNode.jsandMulter.Thistutorialcoveredthesetupoftheprojectenvironment,installationofdependencies,configurationofMultermiddleware,creationofthefrontendinterface,implementationofdranddropfunctionality,handlingfileuploadsontheserver,anddisplayinguploadprogress.CompleteSourceCodeserver.js constexpress=require('express'); constmulter=require('multer'); constpath=require('path'); constapp=express(); constPORT=3000; app.use(express.static(__dirname)); //SetupMulterstore conststore=multer.diskStore({ destination:function(request,file,callback){ callback(null,'uploads/'); }, filename:function(request,file,callback){ callback(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname)); } }); //InitializeMulterupload constupload=multer({store:store}); app.get('/upload',async(request,response)=>{ response.sendFile(__dirname+'/upload.html'); }); app.post('/upload',upload.single('file'),(request,response)=>{ response.json({filename:request.file.filename}); }); app.listen(PORT,()=>{ console.log(`Serverisrunningonport${PORT}`); }); upload.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>DrandDropFileUpload</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5"><b>DrandDropFileUploadinNode.js</b></h1> <divid="drop_zone"> <p>Dranddropfileshere</p> </div> <br/> <divclass="cardmb-5"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">UploadedFile</div> <divclass="colcol-6"></div> </div> </div> <divid="uploadedIme"class="card-body"> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <style> #drop_zone{ width:100%; min-height:200px; border:2pxdashed#ccc; border-radius:10px; padding:20px; box-sizing:border-box; display:flex; justify-content:center; align-items:center; flex-direction:column; } #drop_zone.hover{ background-color:#f0f0f0; } </style> <script> vardropZone=document.getElementById('drop_zone'); dropZone.addEventListener('drover',(event)=>{ event.preventDefault(); dropZone.classList.add('hover'); }); dropZone.addEventListener('drlee',(event)=>{ event.preventDefault(); dropZone.classList.remove('hover'); }); dropZone.addEventListener('drop',(event)=>{ event.preventDefault(); dropZone.classList.remove('hover'); varfiles=event.dataTransfer.files; handlesFiles(files); }); functionhandlesFiles(files){ for(varcount=0;count<files.length;count++){ varfile=files[count]; uploadFile(file); } } functionuploadFile(file){ varformData=newFormData(); formData.append('file',file); fetch('/upload',{ method:'POST', body:formData }) .then(response=>response.json()) .then(data=>{ constgallery=document.getElementById('uploadedIme'); lethtml=`<imgsrc="/uploads/${data.filename}"class="img-thumbnail"/>`; gallery.innerHTML=gallery.innerHTML+html; }); } </script> ShareThis:   Facebook Twitter Google+ Stumble DiggReadMoreWednesday28February2024Node.jsCRUDApplicationwithMongoDBDatabase Webslesson    23:23    crud,MongoDB,mongodbcrud,mongodbcrudoperations,node,nodejs,nodejscrud,nodejsmongodbcrud,nodejstutorial,nodemongodbcrud,nodejs,programmingtutorial,webdevelopment    Nocomments   Introduction:Inthistutorial,we'llwalkthroughtheprocessofbuildingaCRUD(Create,Read,Update,Delete)applicationusingNode.jsandMongoDB.CRUDapplicationsarefundamentalinwebdevelopmentastheyfacilitatethebasicoperationsformaningdatainadatabase.We'llleverethepowerofNode.jsforthebackendlogicandMongoDBasthedatabasetostoreourdata.Bytheendofthistutorial,you'llheasolidunderstandingofhowtocreateafullyfunctionalCRUDapplication.DownloadSourceCodePrerequisites:Beforewebegin,makesureyouhethefollowinginstalledonyoursystem:Node.jsMongoDBStep1:SettingUpYourProject:Startbycreatinganewdirectoryforyourprojectandnigateintoitusingyourterminalorcommandprompt. mkdirnode-crud-app cdnode-crud-app InitializeanewNode.jsprojectusingnpm. npminit-y Step2:InstallingDependencies:Next,weneedtoinstallthenecessarydependenciesforourproject.We'lluseExpress.jsasourwebframeworkandMongooseastheMongoDBODM(ObjectDataModeling)library. npminstallexpressmongoosebody-parser Step3:SettingUpMongoDB:Inthistutorial,weheuseCloudMongoDBDatabase.Soinbelowvideotutorial,youcanfindstepbystepguideforhowtocreateMongoDBSchemaorDatabaseintheCloud.Step4:CreatingtheServer:Createafilenamedserver.jsinyourprojectdirectoryandsetupabasicExpressserver.server.js constexpress=require('express'); constbodyParser=require('body-parser'); constmongoose=require('mongoose'); constapp=express(); constPORT=3000; app.use(bodyParser.json()); app.use(express.static(__dirname)); Step5:ConnectingtoMongoDB:AddthecodetoconnectyourNode.jsapplicationtoMongoDBusingMongoose.server.js constexpress=require('express'); constbodyParser=require('body-parser'); constmongoose=require('mongoose'); constapp=express(); constPORT=3000; app.use(bodyParser.json()); app.use(express.static(__dirname)); mongoose.connect('mongodb+srvjohnsmith174:xxxxx@cluster0.8dbkdwt.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0'); constconnect=mongoose.connection; connect.on('error',console.error.bind(console,'MongoDBconnectionerror:')); connect.once('open',()=>{ console.log('ConnectedtoMongoDB'); }); Step6:CreatingModels:DefineaschemaforyourMongoDBdocumentsandcreatemodelsusingMongoose.server.js constuserSchema=newmongoose.Schema({ name:String, email:String, e:Number }); constUser=mongoose.model('User',userSchema); Step7:ImplementingCRUDOperations:Now,let'simplementtheCRUDoperationsforourapplication-Create,Read,Update,andDelete.CreateOperation(POST):Thecreateoperationinvolvesaddingnewitemstoourdatabase.We'lldefinearoutetohandleincomingPOSTrequeststocreatenewitems.Sofirstwehetocreateonegetrouteinserver.jsfileforloadHTMLfileinthebrowser.server.js app.get('/',async(request,response)=>{ response.sendFile(__dirname+'/user.html'); }); Nextwehetocreateoneuser.htmlfileandunderthisfile,wehetocreateonebuttonandwhenweheclickonbuttonthenbootstrapmodalmustbepopuponwebpeandundermodalwewillmakeuserformforinsertdataintoMongoDB.user.html <!doctypehtml><htmllang="en"><head><!--Requiredmetats--><metacharset="utf-8"><metaname="viewport"content="width=device-width,initial-scale=1"><!--BootstrapCSS--><linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"><title>BuildaCRUDAppwithNode.jsandMongoDB</title></head><body><divclass="container"><h1class="text-centermb-5mt-5text-danger"><b>BuildaCRUDAppwithNode.jsandMongoDB-InsertDataintoMongoDBDatabase-2</b></h1><divclass="cardmb-5"><divclass="card-header"><divclass="row"><divclass="colcol-6">SampleData</div><divclass="colcol-6"><buttontype="button"class="btnbtn-primarybtn-smfloat-end"onclick="makeModal('AddUser','Add','insertData')">Add</button></div></div></div><divclass="card-body"><divclass="table-responsive"></div></div></div></div></body></html><scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script><divid="modalArea"></div><script>varuserModalElement;functionmakeModal(title,button_value,callback){lethtml=`<divclass="modal"tabindex="-1"id="userModal"><divclass="modal-dialog"><divclass="modal-content"><formid="userform"><divclass="modal-header"><h5class="modal-title">${title}</h5><buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button></div><divclass="modal-body"><divclass="mb-3"><label>Name</label><inputtype="text"name="name"id="name"class="form-control"/></div><divclass="mb-3"><label>Email</label><inputtype="email"name="email"id="email"class="form-control"/></div><divclass="mb-3"><label>e</label><inputtype="number"name="e"id="e"class="form-control"/></div></div><divclass="modal-footer"><buttontype="button"class="btnbtn-secondary"data-bs-dismiss="modal">Close</button><buttontype="button"class="btnbtn-primary"onclick="${callback}()">${button_value}</button></div></form></div></div></div>`;document.querySelector('#modalArea').innerHTML=html;userModalElement=newbootstrap.Modal(document.getElementById('userModal'));userModalElement.show();}functioninsertData(){letformElement=document.getElementById('userform');constformData=newFormData(formElement);//ConvertformDatatoJSONconstjsonData={};formData.forEach((value,key)=>{jsonData[key]=value;});//MakeaPOSTrequestusingFetchAPIfetch('/users',{method:'POST',body:JSON.stringify(jsonData),headers:{'Content-Type':'application/json'}}).then(response=>{returnresponse.json();}).then(data=>{userModalElement.hide();getData();});}</script>Nextwehegoestoserver.jsfileandherewehetocreateonePOSTrouteforhandleformdataforinsertdataintoMongoDB.server.js app.post('/users',async(request,response)=>{ constuser=newUser({ name:request.body.name, email:request.body.email, e:request.body.e }); constnewItem=awaituser.se(); response.status(201).json({scuccess:true}); }); ReadOperation(GET):Soforreaddataoperation,firstwehegoesttouser.htmlfileandherewehetocreateoneHTMLtableandthenafterwehegoestoJaScriptcodepart,andherewehetocreateonegetData()functionwhichwillsendfetchdatarequesttonodeapplicationrouteanddisplayonwebpe,andcallthisfunctionintoinsertData()function,sowhennewdatahasbeeninsertedthenitwilldisplaylastinserteddataonwebalso.user.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>BuildaCRUDAppwithNode.jsandMongoDB</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5text-danger"><b>BuildaCRUDAppwithNode.jsandMongoDB-InsertDataintoMongoDBDatabase-2</b></h1> <divclass="cardmb-5"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">SampleData</div> <divclass="colcol-6"> <buttontype="button"class="btnbtn-primarybtn-smfloat-end"onclick="makeModal('AddUser','Add','insertData')">Add</button> </div> </div> </div> <divclass="card-body"> <divclass="table-responsive"> <tableclass="tabletable-borderedtable-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>e</th> <th>Action</th> </tr> </thead> <tbodyid="dataArea"></tbody> </table> </div> </div> </div> </div> </body> </html> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> <divid="modalArea"></div> <script> varuserModalElement; functionmakeModal(title,button_value,callback) { lethtml=` <divclass="modal"tabindex="-1"id="userModal"> <divclass="modal-dialog"> <divclass="modal-content"> <formid="userform"> <divclass="modal-header"> <h5class="modal-title">${title}</h5> <buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button> </div> <divclass="modal-body"> <divclass="mb-3"> <label>Name</label> <inputtype="text"name="name"id="name"class="form-control"/> </div> <divclass="mb-3"> <label>Email</label> <inputtype="email"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label>e</label> <inputtype="number"name="e"id="e"class="form-control"/> </div> </div> <divclass="modal-footer"> <buttontype="button"class="btnbtn-secondary"data-bs-dismiss="modal">Close</button> <buttontype="button"class="btnbtn-primary"onclick="${callback}()">${button_value}</button> </div> </form> </div> </div> </div> `; document.querySelector('#modalArea').innerHTML=html; userModalElement=newbootstrap.Modal(document.getElementById('userModal')); userModalElement.show(); } functioninsertData() { letformElement=document.getElementById('userform'); constformData=newFormData(formElement); //ConvertformDatatoJSON constjsonData={}; formData.forEach((value,key)=>{ jsonData[key]=value; }); //MakeaPOSTrequestusingFetchAPI fetch('/users',{ method:'POST', body:JSON.stringify(jsonData), headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ userModalElement.hide(); getData(); }); } getData(); functiongetData(){ fetch('/users') .then(response=>{ returnresponse.json(); }) .then(data=>{ lethtml=''; if(data.length>0){ data.map((row)=>{ html+=` <tr> <td>${row.name}</td> <td>${row.email}</td> <td>${row.e}</td> <td></td> </tr> `; }); }else{ html='<tr><tdcolspan="4"class="text-center">NoDataFound</td></tr>'; } document.getElementById('dataArea').innerHTML=html; }); } </script> NextThereadoperationinvolvesfetchingexistingitemsfromthedatabase.We'lldefinearoutetohandleincomingGETrequeststoretrieveitemsinserver.jsfile.server.js app.get('/users',async(request,response)=>{ constusers=awaitUser.find(); response.status(200).json(users); }); UpdateOperation(PUT/PATCH):ForUpdateMongoDBdata,firstwehegoestouser.htmlfileandunderthisfile,wehetocreateeditbuttonineachofdata,whichwillsendgetrequestforfetchsingleuserdatafromMongoDBdataandthenafterwehetocreateoneeditData()functionwhichwillbecalledwhenwehesubmitformdata.SoitwillsendPUTrequesttonodecrudapplication.user.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>BuildaCRUDAppwithNode.jsandMongoDB</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5text-danger"><b>BuildaCRUDAppwithNode.jsandMongoDB-DeleteDatafromMongoDBDatabase-5</b></h1> <divclass="cardmb-5"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">SampleData</div> <divclass="colcol-6"> <buttontype="button"class="btnbtn-primarybtn-smfloat-end"onclick="makeModal('AddUser','Add','insertData')">Add</button> </div> </div> </div> <divclass="card-body"> <divclass="table-responsive"> <tableclass="tabletable-borderedtable-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>e</th> <th>Action</th> </tr> </thead> <tbodyid="dataArea"></tbody> </table> </div> </div> </div> </div> </body> </html> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> <divid="modalArea"></div> <script> varuserModalElement; functionmakeModal(title,button_value,callback) { lethtml=` <divclass="modal"tabindex="-1"id="userModal"> <divclass="modal-dialog"> <divclass="modal-content"> <formid="userform"> <divclass="modal-header"> <h5class="modal-title">${title}</h5> <buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button> </div> <divclass="modal-body"> <divclass="mb-3"> <label>Name</label> <inputtype="text"name="name"id="name"class="form-control"/> </div> <divclass="mb-3"> <label>Email</label> <inputtype="email"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label>e</label> <inputtype="number"name="e"id="e"class="form-control"/> </div> </div> <divclass="modal-footer"> <inputtype="hidden"name="user_id"id="user_id"/> <buttontype="button"class="btnbtn-secondary"data-bs-dismiss="modal">Close</button> <buttontype="button"class="btnbtn-primary"onclick="${callback}()">${button_value}</button> </div> </form> </div> </div> </div> `; document.querySelector('#modalArea').innerHTML=html; userModalElement=newbootstrap.Modal(document.getElementById('userModal')); userModalElement.show(); } functioninsertData() { letformElement=document.getElementById('userform'); constformData=newFormData(formElement); //ConvertformDatatoJSON constjsonData={}; formData.forEach((value,key)=>{ jsonData[key]=value; }); //MakeaPOSTrequestusingFetchAPI fetch('/users',{ method:'POST', body:JSON.stringify(jsonData), headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ userModalElement.hide(); getData(); }); } getData(); functiongetData(){ fetch('/users') .then(response=>{ returnresponse.json(); }) .then(data=>{ lethtml=''; if(data.length>0){ data.map((row)=>{ html+=` <tr> <td>${row.name}</td> <td>${row.email}</td> <td>${row.e}</td> <td> <buttontype="button"class="btnbtn-warningbtn-sm"onclick="fetchSingleData('${row._id}')">Edit</button> </td> </tr> `; }); }else{ html='<tr><tdcolspan="4"class="text-center">NoDataFound</td></tr>'; } document.getElementById('dataArea').innerHTML=html; }); } functionfetchSingleData(id){ fetch(`/users/${id}`) .then(response=>{ returnresponse.json(); }) .then(data=>{ makeModal('EditUser','Edit','editData'); document.getElementById('name').value=data.name; document.getElementById('email').value=data.email; document.getElementById('e').value=data.e; document.getElementById('user_id').value=data._id; }); } functioneditData(){ letformElement=document.getElementById('userform'); constformData=newFormData(formElement); letjsonData={}; formData.forEach((value,key)=>{ jsonData[key]=value; }); constuserId=document.getElementById('user_id').value; fetch(`/users/${userId}`,{ method:'PUT', body:JSON.stringify(jsonData), headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ userModalElement.hide(); getData(); }); } </script> Theupdateoperationinvolvesmodifyingexistingitemsinthedatabase.We'lldefinearoutetohandleincomingPUTorPATCHrequeststoupdateitems.server.js app.get('/users/:id',async(request,response)=>{ constuser=awaitUser.findById(request.params.id); response.status(200).json(user); }); app.put('/users/:id',async(request,response)=>{ constuserId=request.params.id; //Fetchtheuserfromthedatabase constuser=awaitUser.findById(userId); user.name=request.body.name; user.email=request.body.email; user.e=request.body.e; constupdatedItem=awaituser.se(); response.status(200).json(updatedItem); }); DeleteOperation(DELETE):ForDeleteMongoDBDatafromNodeCRUDApplication,sofirstwehetocreateDeletebuttonineachrowofdatainuser.htmlfileandthenafterwehetocreatedeleteData()JaScriptfunctionwhichwillsendDELETEdatarequesttonoderoutebyusingDELETEPOSTmethod.user.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>BuildaCRUDAppwithNode.jsandMongoDB</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5text-danger"><b>BuildaCRUDAppwithNode.jsandMongoDB-DeleteDatafromMongoDBDatabase-5</b></h1> <divclass="cardmb-5"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">SampleData</div> <divclass="colcol-6"> <buttontype="button"class="btnbtn-primarybtn-smfloat-end"onclick="makeModal('AddUser','Add','insertData')">Add</button> </div> </div> </div> <divclass="card-body"> <divclass="table-responsive"> <tableclass="tabletable-borderedtable-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>e</th> <th>Action</th> </tr> </thead> <tbodyid="dataArea"></tbody> </table> </div> </div> </div> </div> </body> </html> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> <divid="modalArea"></div> <script> varuserModalElement; functionmakeModal(title,button_value,callback) { lethtml=` <divclass="modal"tabindex="-1"id="userModal"> <divclass="modal-dialog"> <divclass="modal-content"> <formid="userform"> <divclass="modal-header"> <h5class="modal-title">${title}</h5> <buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button> </div> <divclass="modal-body"> <divclass="mb-3"> <label>Name</label> <inputtype="text"name="name"id="name"class="form-control"/> </div> <divclass="mb-3"> <label>Email</label> <inputtype="email"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label>e</label> <inputtype="number"name="e"id="e"class="form-control"/> </div> </div> <divclass="modal-footer"> <inputtype="hidden"name="user_id"id="user_id"/> <buttontype="button"class="btnbtn-secondary"data-bs-dismiss="modal">Close</button> <buttontype="button"class="btnbtn-primary"onclick="${callback}()">${button_value}</button> </div> </form> </div> </div> </div> `; document.querySelector('#modalArea').innerHTML=html; userModalElement=newbootstrap.Modal(document.getElementById('userModal')); userModalElement.show(); } functioninsertData() { letformElement=document.getElementById('userform'); constformData=newFormData(formElement); //ConvertformDatatoJSON constjsonData={}; formData.forEach((value,key)=>{ jsonData[key]=value; }); //MakeaPOSTrequestusingFetchAPI fetch('/users',{ method:'POST', body:JSON.stringify(jsonData), headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ userModalElement.hide(); getData(); }); } getData(); functiongetData(){ fetch('/users') .then(response=>{ returnresponse.json(); }) .then(data=>{ lethtml=''; if(data.length>0){ data.map((row)=>{ html+=` <tr> <td>${row.name}</td> <td>${row.email}</td> <td>${row.e}</td> <td> <buttontype="button"class="btnbtn-warningbtn-sm"onclick="fetchSingleData('${row._id}')">Edit</button> <buttontype="button"class="btnbtn-dangerbtn-sm"onclick="deleteData('${row._id}')">Delete</button> </td> </tr> `; }); }else{ html='<tr><tdcolspan="4"class="text-center">NoDataFound</td></tr>'; } document.getElementById('dataArea').innerHTML=html; }); } functionfetchSingleData(id){ fetch(`/users/${id}`) .then(response=>{ returnresponse.json(); }) .then(data=>{ makeModal('EditUser','Edit','editData'); document.getElementById('name').value=data.name; document.getElementById('email').value=data.email; document.getElementById('e').value=data.e; document.getElementById('user_id').value=data._id; }); } functioneditData(){ letformElement=document.getElementById('userform'); constformData=newFormData(formElement); letjsonData={}; formData.forEach((value,key)=>{ jsonData[key]=value; }); constuserId=document.getElementById('user_id').value; fetch(`/users/${userId}`,{ method:'PUT', body:JSON.stringify(jsonData), headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ userModalElement.hide(); getData(); }); } functiondeleteData(id){ if(confirm("Areyousureyouwanttodeletethis?")){ fetch(`/users/${id}`,{ method:'DELETE', headers:{ 'Content-Type':'application/json' } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ getData(); }); } } </script> Thedeleteoperationinvolvesremovingitemsfromthedatabase.We'lldefinearoutetohandleincomingDELETErequeststodeleteitems.server.js app.delete('/users/:id',async(request,response)=>{ constuserId=request.params.id; //Fetchtheuserfromthedatabase constuser=awaitUser.findById(userId); awaituser.deleteOne(); response.status(200).json({messe:'Deleteditem'}); }); DownloadSourceCodeStep8:TestingYourApplication:FortestMongoDBNode.jsCRUDapplicationinbrowser,sowehegoestoterminalandrunnodeserver.jsthiscommandwhichwillstartNodeDevelopmentserverandprovideushttplocalhost:3000/baseurlofourNodeApplication.Conclusion:Congratulations!You'vesuccessfullybuiltaNode.jsCRUDapplicationwithMongoDB.Thistutorialcoveredthebasics,butthere'sstillroomforimprovementandexpansion.Feelfreetoexploreadditionalfeaturesandfunctionalitiestoenhanceyourapplicationfurther.ShareThis:   Facebook Twitter Google+ Stumble DiggReadMoreTuesday20February2024ConvertingDynamicHTMLtoPDFinNode.jswithPuppeteer Webslesson    23:04    html2pdf,htmltopdf,htmltopdfnode,nodepdf,nodejs,nodejscreatepdf,nodejspdf,nodejspdfcreate,pdf-creator-node,Puppeteer,PuppeteerHTMLtoPDF,webdevelopment    Nocomments   Inthistutorial,we'lllearnhowtoconvertHTMLcontenttoaPDFfileusingPuppeteerinaNode.jsenvironment.PuppeteerisaNodelibrarythatprovidesahigh-levelAPItocontrolheadlessChromeorChromiumovertheDevToolsProtocol,makingitapowerfultoolforautomatingwebtasks,includinggeneratingPDFfilesfromHTMLcontent.PrerequisitesBeforewebegin,ensureyouhethefollowinginstalled: Node.js(withnpm) MySQL(forthedatabasesetup,optionalforthistutorial) BasicunderstandingofNode.jsandJaScriptSettinguptheProjectFirst,let'ssetupaNode.jsprojectandinstallthenecessarydependencies.Createanewdirectoryforyourprojectandnigateintoit: mkdirhtml-to-pdf-nodejs cdhtml-to-pdf-nodejs InitializeanewNode.jsproject: npminit-y Installtherequireddependencies(Express,MySQL,Puppeteer,Open): npminstallexpressmysql2puppeteeropen DatabaseStructureForconvertdynamicHTMLtoPDFweneedtofetchdatafromMySQLtable.Sorunbelowsqlscriptwhichwillcreatesampledatatableinyourdatabase. CREATETABLE`sampledata`( `id`mediumintunsignedNOTNULLAUTO_INCREMENT, `name`varchar(255)DEFAULTNULL, `phone`varchar(100)DEFAULTNULL, `email`varchar(255)DEFAULTNULL, `address`varchar(255)DEFAULTNULL, `postalZip`varchar(10)DEFAULTNULL, `region`varchar(50)DEFAULTNULL, `country`varchar(100)DEFAULTNULL, PRIMARYKEY(`id`) )ENGINE=InnoDBAUTO_INCREMENT=26DEFAULTCHARSET=utf8mb4COLLATE=utf8mb4_0900_ai_ci; INSERTINTO`sampledata`VALUES(1,'StephenTaylor','1-','auctor.nunc@hotmail.com','5659LuctusRd.','','DadraandNarHeli','Poland'),(2,'MasonGeorge','1-','mauris@aol.edu','Ap#221-6699Lacus.St.','','FATA','CostaRica'),(3,'HasadDonaldson','1-','et.euismod@google.edu','Ap#383-4682Ornare.','','Kinross-shire','UnitedKingdom'),(4,'HallHolland','(805)418-1538','tempor.est@icloud.com','P.O.Box358,7624Tinciduntenue','','Madrid','Indonesia'),(5,'AdamHampton','1-','cubilia.curae@google.ca','P.O.Box161,1859Iaculis.','','BrusselsHoofdstedelijkGewest','SouthKorea'),(6,'ElizabethAllison','(538)834-6212','elit.dictum@hotmail.edu','867-6580AtSt.','','Jeju','Pakistan'),(7,'NeveBarber','1-','vestibulum.nec.euismod@google.com','224-8122DonecRoad','','SantaCatarina','Netherlands'),(8,'FatimaPope','(619)278-1176','nulla.integer@hotmail.couk','649-1054IpsumRd.','','Bahia','Austria'),(9,'ShadCobb','1-','dignissim.maecenas.ornare@outlook.edu','6983Mna.Rd.','2163','Xīběi','Philippines'),(10,'ZephrRuiz','1-','luctus.ipsum@google.ca','634-2043Crasenue','3845','Mecklenburg-Vorpommern','Sweden'),(11,'JulietLynn','(375)573-6793','proin.dolor.nulla@yahoo.net','Ap#179-6441CumRd.','','Calabria','Turkey'),(12,'CandiceMedina','1-','integer.vulputate@icloud.org','953-188EtRd.','','Vorarlberg','Australia'),(13,'RheaRoach','(635)768-6867','vitae.velit@icloud.edu','543-5616Sem.','','Burgenland','Canada'),(14,'DeanHendrix','(362)760-8321','nunc.pulvinar@protonmail.ca','Ap#905-5267ArcuStreet','6755-4242','NationalCapitalRegion','Indonesia'),(15,'MalachiMitchell','1-','eget.lacus.mauris@icloud.ca','P.O.Box183,1479Massa.St.','','VästraGötalandslän','Indonesia'),(21,'GabrielAcevedo','1-','dictum.cursus@outlook.com','5681SitRd.','','Lombardia','Italy'),(22,'BeauNorris','1-','eros@google.edu','Ap#533-2583DuisRd.','R8T1S4','EasternVisayas','UnitedStates'),(23,'KylanMckinney','1-','eleifend.vitae@hotmail.net','333-2972Nec,Road','','Leinster','Australia'),(24,'StoneParsons','1-','aenean@outlook.com','923-5509EtiamStreet','Y1R5X7','ZamboangaPeninsula','Nigeria'),(25,'NeveSweet','(764)167-2572','tellus.aenean@aol.net','558-1070Sed,St.','1023PS','Vienna','UnitedKingdom'); CreatingtheServerandHTMLTemplateNow,let'screateabasicExpressserverthatservesanHTMLpewithsampledatafetchedfromaMySQLdatabase.We'llalsoincludeabuttontotriggertheconversionoftheHTMLtoaPDFfile.Createafilenamedapp.jswiththefollowingcontent:app.js constexpress=require('express'); constmysql=require('mysql2'); //Addpuppeteerlibrary constpuppeteer=require('puppeteer'); constapp=express(); constport=3000; app.use(express.json()); //Servestaticfiles(includingindex.html)fromtherootdirectory app.use(express.static(__dirname)); constdatabase=mysql.createConnection({ host:'localhost', user:'root', password:'9', database:'testing' }); database.connect((error)=>{ if(error){ console.error('ErrorconnectingtoMySQL:',error); }else{ console.log('ConnectedtoMySQLdatabase'); } }); app.get('/data',(request,response)=>{ response.sendFile(__dirname+'/data.html'); }); app.post('/getData',(request,response)=>{ database.query('SELECT*FROMsampledata',async(error,results)=>{ response.status(200).json(results); }); }); app.listen(port,()=>{ console.log(`Serverisrunningonhttplocalhost:${port}`); }); Createafilenameddata.htmlwiththefollowingcontent: <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>HowtoConvertHTMLtoPDFinNode.jsusingPuppeteer</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">HowtoConvertHTMLtoPDFinNode.jsusingPuppeteer</h1> <divclass="card"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">SampleData</div> <divclass="colcol-6"> <ahref="/convertPDF"class="btnbtn-primarybtn-smfloat-end">DownloadinPDF</a> </div> </div> </div> <divclass="card-body"> <divclass="table-responsive"> <tableclass="tabletable-borderedtable-striped"> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Email</th> <th>Address</th> <th>Zip</th> <th>Region</th> <th>Country</th> </tr> </thead> <tbodyid="dataArea"></tbody> </table> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> getData(); functiongetData(){ fetch('/getData',{ method:'POST' }) .then(response=>{ returnresponse.json(); }) .then(data=>{ if(data.length>0){ lethtml=''; for(leti=0;i<data.length;i++){ html+=` <tr> <td>${data[i].name}</td> <td>${data[i].phone}</td> <td>${data[i].email}</td> <td>${data[i].address}</td> <td>${data[i].postalZip}</td> <td>${data[i].region}</td> <td>${data[i].country}</td> </tr> `; } document.getElementById('dataArea').innerHTML=html; } }) .catch(error=>{ //Handleerrors //console.error(error); alert(error); }); } </script> Sethiscodeintherootdirectoryofyourproject.HTMLtoPDFConversionWe'lldefineafunctionconvertHTMLToPDFinapp.jsfilethattakesHTMLcontentasinput,convertsittoaPDFfileusingPuppeteer,andopensthegeneratedPDFfile.app.js asyncfunctionconvertHTMLToPDF(htmlContent,pdfFilePath,margins={top:'10mm',right:'10mm',bottom:'10mm',left:'10mm'}){ constbrowser=awaitpuppeteer.launch(); constpe=awaitbrowser.newPe(); //Setthepecontent awaitpe.setContent(htmlContent); //GeneratePDF awaitpe.pdf({path:pdfFilePath,format:'A4',margin:margins}); //OpenthegeneratedPDFfileinthedefaultPDFviewer constopen=awaitimport('open'); awaitopen.default(pdfFilePath); //closethebrowser awaitbrowser.close(); } ServingHTMLandTriggeringConversionFinally,we'llsetuproutestofetchdatafromMySQLtableandconvertintoHTMLandservetheHTMLdataandtriggertheconversiontoPDFwhentheuserclicksonDownloadinPDFbutton.app.js app.get('/convertPDF',async(request,response)=>{ database.query('SELECT*FROMsampledata',async(error,results)=>{ lethtml=''; if(results.length>0){ html+=` <tablewidth="100%"border="1"cellpadding="5"cellspacing="0"> <tr> <thwidth="20%">Name</th> <thwidth="10%">Phone</th> <thwidth="20%">Email</th> <thwidth="20%">Address</th> <thwidth="10%">Zip</th> <thwidth="10%">Region</th> <thwidth="10%">Country</th> </tr> `; results.map((row)=>{ html+=` <tr> <th>${row.name}</th> <th>${row.phone}</th> <th>${row.email}</th> <th>${row.address}</th> <th>${row.postalZip}</th> <th>${row.region}</th> <th>${row.country}</th> </tr> `; }); html+=` </table> `; } awaitconvertHTMLToPDF(html,'data.pdf'); }); }); RunningtheServerToruntheserver,executethefollowingcommand: nodeapp.js Visithttplocalhost:3000/datainyourwebbrowsertoseethesampledatatable.Clickthe"DownloadinPDF"buttontoconverttheHTMLtabletoaPDFfile.ConclusionCongratulations!You'velearnedhowtoconvertHTMLcontenttoaPDFfileinNode.jsusingPuppeteer.ThistechniquecanbeusefulforgeneratingPDFreports,invoices,oranyotherprintabledocumentsfromdynamicHTMLcontent.FeelfreetocustomizethecodetosuityourspecificrequirementsandexploreadditionalfeaturesofferedbyPuppeteerforwebautomationandPDFgeneration.CompleteSourceCodeapp.js constexpress=require('express'); constmysql=require('mysql2'); //Addpuppeteerlibrary constpuppeteer=require('puppeteer'); constapp=express(); constport=3000; app.use(express.json()); //Servestaticfiles(includingindex.html)fromtherootdirectory app.use(express.static(__dirname)); constdatabase=mysql.createConnection({ host:'localhost', user:'root', password:'9', database:'testing' }); database.connect((error)=>{ if(error){ console.error('ErrorconnectingtoMySQL:',error); }else{ console.log('ConnectedtoMySQLdatabase'); } }); app.get('/data',(request,response)=>{ response.sendFile(__dirname+'/data.html'); }); app.post('/getData',(request,response)=>{ database.query('SELECT*FROMsampledata',async(error,results)=>{ response.status(200).json(results); }); }); asyncfunctionconvertHTMLToPDF(htmlContent,pdfFilePath,margins={top:'10mm',right:'10mm',bottom:'10mm',left:'10mm'}){ constbrowser=awaitpuppeteer.launch(); constpe=awaitbrowser.newPe(); //Setthepecontent awaitpe.setContent(htmlContent); //GeneratePDF awaitpe.pdf({path:pdfFilePath,format:'A4',margin:margins}); //OpenthegeneratedPDFfileinthedefaultPDFviewer constopen=awaitimport('open'); awaitopen.default(pdfFilePath); //closethebrowser awaitbrowser.close(); } app.get('/convertPDF',async(request,response)=>{ database.query('SELECT*FROMsampledata',async(error,results)=>{ lethtml=''; if(results.length>0){ html+=` <tablewidth="100%"border="1"cellpadding="5"cellspacing="0"> <tr> <thwidth="20%">Name</th> <thwidth="10%">Phone</th> <thwidth="20%">Email</th> <thwidth="20%">Address</th> <thwidth="10%">Zip</th> <thwidth="10%">Region</th> <thwidth="10%">Country</th> </tr> `; results.map((row)=>{ html+=` <tr> <th>${row.name}</th> <th>${row.phone}</th> <th>${row.email}</th> <th>${row.address}</th> <th>${row.postalZip}</th> <th>${row.region}</th> <th>${row.country}</th> </tr> `; }); html+=` </table> `; } awaitconvertHTMLToPDF(html,'data.pdf'); }); }); app.listen(port,()=>{ console.log(`Serverisrunningonhttplocalhost:${port}`); }); data.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>HowtoConvertHTMLtoPDFinNode.jsusingPuppeteer</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">HowtoConvertHTMLtoPDFinNode.jsusingPuppeteer</h1> <divclass="card"> <divclass="card-header"> <divclass="row"> <divclass="colcol-6">SampleData</div> <divclass="colcol-6"> <ahref="/convertPDF"class="btnbtn-primarybtn-smfloat-end">DownloadinPDF</a> </div> </div> </div> <divclass="card-body"> <divclass="table-responsive"> <tableclass="tabletable-borderedtable-striped"> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Email</th> <th>Address</th> <th>Zip</th> <th>Region</th> <th>Country</th> </tr> </thead> <tbodyid="dataArea"></tbody> </table> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> getData(); functiongetData(){ fetch('/getData',{ method:'POST' }) .then(response=>{ returnresponse.json(); }) .then(data=>{ if(data.length>0){ lethtml=''; for(leti=0;i<data.length;i++){ html+=` <tr> <td>${data[i].name}</td> <td>${data[i].phone}</td> <td>${data[i].email}</td> <td>${data[i].address}</td> <td>${data[i].postalZip}</td> <td>${data[i].region}</td> <td>${data[i].country}</td> </tr> `; } document.getElementById('dataArea').innerHTML=html; } }) .catch(error=>{ //Handleerrors //console.error(error); alert(errWebslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorialor); }); } </script> ShareThis:   Facebook Twitter Google+ Stumble DiggReadMoreTuesday13February2024SimplifyingUserAuthenticationwithJWTTokensinNode.js Webslesson    04:17    authentication,authenticationnodejs,authorization,js,jwt,jwtauthentication,jwtauthenticationnodejs,login,node,nodejs,node.js,nodejs,register,registration,token,tutorial,webdevelopment    Nocomments   Inmodernwebdevelopment,userauthenticationisafundamentalaspectofbuildingsecureapplications.ImplementingaloginandregistrationsystemusingJSONWebTokens(JWT)inNode.jsoffersarobustsolutionthatenhancessecurityandsimplifiesusermanement.Inthisarticle,we'llexplorehowtoimplementuserauthenticationusingJWTtokensinaNode.jsapplication.WhatareJWTTokens?JWTtokensareanopenstandard(RFC7519)thatdefinesacompactandself-containedwayforsecurelytransmittinginformationbetweenpartiesasaJSONobject.Thesetokenscanbesignedusingasecretorapublic/privatekeypair,providingameansofverifyingtheintegrityoftheinformationcontainedwithin. Step1:SettingUpYourNode.jsEnvironment Step2:CreatingtheExpressServer Step3:DatabaseConnection Step4:SettingUpRoutes Step5:ImplementingUserRegistration Step6:ImplementingUserLogin Step7:ProtectingRoutes Step8:RunApplication Step9:ConclusionStep1:SettingUpYourNode.jsEnvironmentEnsureyouheNode.jsinstalledonyourmachine.Ifnot,downloadandinstallitfromtheofficialNode.jswebsite.Onceinstalled,openyourterminalandcreateanewdirectoryforyourproject. mkdirnode-jwt-auth cdnode-jwt-auth InitializeanewNode.jsprojectandinstallthenecessarydependencies. npminstallexpressjsonwebtokenbcryptbody-parsermongoose Step2:CreatingtheExpressServerCreateafilenamedapp.jsandsetupabasicExpressserver.app.js constexpress=require('express'); constmysql=require('mysql2'); constbcrypt=require('bcrypt'); constjwt=require('jsonwebtoken'); constapp=express(); constport=3000; app.use(express.json()); //Servestaticfiles(includingindex.html)fromtherootdirectory app.use(express.static(__dirname)); Step3:DatabaseConnectionUnderthisapp.jsfilewehetomakeMySQLDatabaseconnection.SouserregistrationdatawillbestoredunderMySQLdatabase.app.js constdatabase=mysql.createConnection({ host:'localhost', user:'root', password:'9', database:'testing' }); database.connect((error)=>{ if(error){ console.error('ErrorconnectingtoMySQL:',error); }else{ console.log('ConnectedtoMySQLdatabase'); } }); Itwillmakedatabaseconnectionandalsocheckthatthereisanyerrorhasbeenoccuredduringdatabaseconnection.BelowyoucanfindMySQLtablestructureforusertable.Soyouhetocopythis.sqlcodeandruninlocalMySQLdatabase.Soitwillcreateuserunderwhichregistrationdatawillbestored. CREATETABLE`user`( `user_id`intNOTNULLAUTO_INCREMENT, `user_email`varchar(70)DEFAULTNULL, `user_password`varchar(70)DEFAULTNULL, `user_name`varchar(45)DEFAULTNULL, `email_verification_status`enum('NotVerified','Verified')DEFAULTNULL, PRIMARYKEY(`user_id`) )ENGINE=InnoDBAUTO_INCREMENT=33DEFAULTCHARSET=utf8mb4COLLATE=utf8mb4_0900_ai_ci Step4:SettingUpRoutesCreateroutesunderapp.jsfileforhandlinguserauthenticationandregistration.app.js app.get('/',(request,response)=>{ }); app.post('/register',async(request,response)=>{ }); Defineroutesforuserregistration,login,andprotectedresourcesintherespectivefiles.Step5:ImplementingUserRegistrationFirstwehegoesinto'/'getroute,andunderthiswehetowritefollowingcodewhichwillloadindex.htmlfileonbrowser.app.js app.get('/',(request,response)=>{ response.sendFile(__dirname+'/index.html'); }); Afterthis,wehegoestoindex.htmlfileandunderthiswehetocreateregisterformandthenafterwehetowriteJaScriptcodeforsubmitregisterformdatausingJaScriptfetchAPI.Andherewehealsousetrycatchblockofhandleerroratfrontendside.index.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">Register</div> <divclass="card-body"> <formid="registerForm"> <divclass="mb-3"> <label><b>Name</b></label> <inputtype="text"name="name"id="name"class="form-control"/> </div> <divclass="mb-3"> <label><b>eMail</b></label> <inputtype="text"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label><b>Password</b></label> <inputtype="password"name="password"id="password"class="form-control"/> </div> <inputtype="submit"class="btnbtn-primary"value="Register"/> </form> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> document.getElementById("registerForm").addEventListener('submit',asyncfunction(event){ event.preventDefault(); constname=document.getElementById("name").value; constemail=document.getElementById("email").value; constpassword=document.getElementById("password").value; letmesseArea=document.getElementById("msgArea"); try{ constresponse=awaitfetch('/register',{ method:'POST', headers:{ 'Content-Type':'application/json' }, body:JSON.stringify({name,email,password}) }); if(response.ok){ messeArea.innerHTML='<divclass="alertalert-success">Userregisteredsuccessfully!</div>'; }else{ constdata=awaitresponse.json(); messeArea.innerHTML=`<divclass="alertalert-info">Error:${data.error}</div>`; } }catch(error){ messeArea.innerHTML='<divclass="alertalert-danger">InternalServerError</div>'; } }); </script> Nowinapp.js,implementtherouteforuserregistration.Hashtheuser'spasswordusingbcryptbeforestoringitinthedatabaseandhereithasalsocheckemailisalreadyexistsornotalso.app.js app.post('/register',async(request,response)=>{ try{ const{name,email,password}=request.body; if(!name||!email||!password){ returnresponse.status(400).json({error:'Pleaseprovideallrequiredfields'}); } //Checkiftheemailalreadyexistsinthedatabase database.query('SELECT*FROMuserWHEREuser_email=?',[email],async(error,results)=>{ if(error){ returnresponse.status(500).json({error:'InternalServerError'}); } if(results.length>0){ returnresponse.status(400).json({error:'Emailalreadyexists'}); } consthashedPassword=awaitbcrypt.hash(password,10); //Insertregisterationdata database.query('INSERTINTOuser(user_email,user_password,user_name)VALUES(?,?,?)',[email,hashedPassword,name],(error)=>{ if(error){ console.log(error); returnresponse.status(500).json({error:'InternalServerError'}); } returnresponse.status(201).json({messe:'Userregisteredsuccessfully'}); }); }); }catch(error){ response.status(500).json({error:'InternalServerError'}); } }); app.listen(port,()=>{ console.log(`Serverisrunningonhttplocalhost:${port}`); }); Step6:ImplementingUserLoginNowforcreateLogininthisNodeJSApplication,firstinapp.jsfilewehegocreaterouteforloadloginforminthebrowser.app.js app.get('/login',(request,response)=>{ response.sendFile(__dirname+'/login.html'); }); Soitwillsendlogin.htmlfileinbrowseranddisplayloginloginformonwebpe.Nextwehetocreatelogin.htmlfileandunderthisfile,wewillwriteHTMLcodefordisplayLoginformandJaScriptcodeforsubmitloginformdatatoserver.login.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">Login</div> <divclass="card-body"> <formid="loginForm"> <divclass="mb-3"> <label><b>eMail</b></label> <inputtype="text"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label><b>Password</b></label> <inputtype="password"name="password"id="password"class="form-control"/> </div> <inputtype="submit"class="btnbtn-primary"value="Login"/> </form> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> document.getElementById('loginForm').addEventListener('submit',asyncfunction(event){ event.preventDefault(); constemail=document.getElementById('email').value; constpassword=document.getElementById('password').value; try{ constresponse=awaitfetch('/login',{ method:'POST', headers:{ 'Content-Type':'application/json', }, body:JSON.stringify({email,password}) }); constdata=awaitresponse.json(); if(response.ok){ localStore.setItem('token',data.token); window.location.href='/welcome'; }else{ document.getElementById('msgArea').innerHTML=`<divclass="alertalert-info">Error:${data.error}</div>`; } }catch(error){ document.getElementById('msgArea').innerHTML='<divclass="alertalert-danger">InternalServerError</div>'; } }); </script> Onceloginformdatahasbeensubmittedthenitwillsendlogindatato/loginrouteofapp.jsfile.Andunderthisfileitwillvalidateuserlogindataandhereitalsoalsocomparesimpleloginformpasswordwithhashedformattedpasswordwhichisstoredindatabasebyusingbcryptlibrary.app.js app.post('/login',async(request,response)=>{ try{ const{email,password}=request.body; if(!email||!password){ returnresponse.status(400).json({error:'Pleaseprovideallrequiredfields'}); } database.query('SELECT*FROMuserWHEREuser_email=?',[email],async(error,results)=>{ if(results.length>0){ constuser=results[0]; if(awaitbcrypt.compare(password,user.user_password)){ consttoken=jwt.sign({userId:user.user_id},secretKey,{expiresIn:'1h'}); response.status(200).json({token}); }else{ response.status(401).json({error:'WrongPassword'}); } }else{ response.status(401).json({error:'WrongEmail'}); } }); }catch(error){ response.status(500).json({error:'InternalServerError'}); } }); Step7:ProtectingRoutesOncewehemakeloginpe,whenuserhasbeenloginintosystemthenuserdatahasbeenstoredinJWTtoken.Nowwewanttoverifythatuserhasbeenloginintosystemornot.Soforthiswehetomakeonemiddlewaretocheckuserisloginornot.InmiddlewareitwilldecodeJWTtokendataandthenafterithasauthenticatethatuserisloginornot.Soforthisfirstwehetocreateonebutton,sowhenweheclickonthatbuttonthenitwillsendrequesttoNodeserverrouteforfetchdatafromJWTtoken.Sowhenwehesendrequesttoserver,theninheaderitwillsendencodedJWTtokendata.welcome.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">WelcomePe</div> <divclass="card-body"> <h1class="text-center">WelcomeUser</h1> <pclass="text-center"> <buttontype="button"class="btnbtn-warning"onclick="getJWTData()">GetUserID</button> <buttontype="button"onclick="logout()"class="btnbtn-primary">Logout</button> </p> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> consttoken=localStore.getItem('token'); if(!token){ window.location.href='/login'; } functionlogout(){ localStore.removeItem('token'); window.location.href='/login'; } functiongetJWTData(){ fetch('/getJWTData',{ headers:{ 'Authorization':token } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ alert(`LoginUserIDis-${data.userId}`); }) .catch(error=>{ alert(error); }); } </script> NowatNodebackendsidecode,wehetocreategetJWTDatarouteandunderthisroutewehetoaddverifyTokenmiddleware.SothismiddlewarecodewillbefirstexecutedanditwillfirstreceiveJWTtokendatafromHTTPheader.AndthenafterbyusingJWTlibraryitwillaindecodethatdata.Ifdatahasbeensuccessfullydecodedthatitwillexecuteotherpartofcode.ButSupposethereJWTtokennotfoundinHTTPheadersthenitwilldirectlysenderrortoclientwithoutexecutingnextcode.ButsupposedatahasbeendecodedfromJWTtokenthenitwillsendbackthatdatatoclientwhichwillbepopuponwebpe.SothiswayitwillfetchdatafromJWTtokenunderNodeJSapplication.app.js //MiddlewaretocheckJWTtoken functionverifyToken(request,response,next){ consttoken=request.headers.authorization; if(!token){ returnresponse.status(401).json({error:'Accessdenied.Notokenprovided.'}); } try{ constdecoded=jwt.verify(token,secretKey); request.user=decoded; next(); }catch(error){ response.status(401).json({error:'Invalidtoken'}); } } app.get('/getJWTData',verifyToken,(request,response)=>{ response.status(200).json({userId:request.user.userId}); }); Step8:RunApplicationOnceourcodeisready,nowforcheckoutputinbrowser,wehegoestoterminalandrunnodeapp.jscommandwhichwillstartnodeserver.AndinbrowserwecanopenthisNodeapplicationbyopenhttplocalhost:3000thisurl.Step9:ConclusionYou'vesuccessfullyimplementedaloginandregistrationsystemusingJWTtokensinyourNode.jsapplication.Thisprovidesasecurewaytomaneusersessionsandprotectsensitiveresources.WiththeflexibilityofNode.jsandthesimplicityofJWTtokens,youcannowbuildrobustauthenticationsystemsforyourwebapplications.CompleteSourceCodeapp.js constexpress=require('express'); constmysql=require('mysql2'); constbcrypt=require('bcrypt'); constjwt=require('jsonwebtoken'); constapp=express(); constport=3000; app.use(express.json()); //Servestaticfiles(includingindex.html)fromtherootdirectory app.use(express.static(__dirname)); constdatabase=mysql.createConnection({ host:'localhost', user:'root', password:'9', database:'testing' }); database.connect((error)=>{ if(error){ console.error('ErrorconnectingtoMySQL:',error); }else{ console.log('ConnectedtoMySQLdatabase'); } }); constsecretKey='eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiQWRtaW4iLCJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkphdmFJblVzZSIsImV4cCI6MTcwNjg3ODE1MywiaWF0IjoxNzA2ODc4MTUzfQ.i4j208HUwM7JjLJL98o9EkE68Ia87i694iq7r67zRHM'; app.get('/',(request,response)=>{ response.sendFile(__dirname+'/index.html'); }); app.post('/register',async(request,response)=>{ try{ const{name,email,password}=request.body; if(!name||!email||!password){ returnresponse.status(400).json({error:'Pleaseprovideallrequiredfields'}); } //Checkiftheemailalreadyexistsinthedatabase database.query('SELECT*FROMuserWHEREuser_email=?',[email],async(error,results)=>{ if(error){ returnresponse.status(500).json({error:'InternalServerError'}); } if(results.length>0){ returnresponse.status(400).json({error:'Emailalreadyexists'}); } consthashedPassword=awaitbcrypt.hash(password,10); //Insertregisterationdata database.query('INSERTINTOuser(user_email,user_password,user_name)VALUES(?,?,?)',[email,hashedPassword,name],(error)=>{ if(error){ console.log(error); returnresponse.status(500).json({error:'InternalServerError'}); } returnresponse.status(201).json({messe:'Userregisteredsuccessfully'}); }); }); }catch(error){ response.status(500).json({error:'InternalServerError'}); } }); app.get('/login',(request,response)=>{ response.sendFile(__dirname+'/login.html'); }); app.post('/login',async(request,response)=>{ try{ const{email,password}=request.body; if(!email||!password){ returnresponse.status(400).json({error:'Pleaseprovideallrequiredfields'}); } database.query('SELECT*FROMuserWHEREuser_email=?',[email],async(error,results)=>{ if(results.length>0){ constuser=results[0]; if(awaitbcrypt.compare(password,user.user_password)){ consttoken=jwt.sign({userId:user.user_id},secretKey,{expiresIn:'1h'}); response.status(200).json({token}); }else{ response.status(401).json({error:'WrongPassword'}); } }else{ response.status(401).json({error:'WrongEmail'}); } }); }catch(error){ response.status(500).json({error:'InternalServerError'}); } }); app.get('/welcome',(request,response)=>{ response.sendFile(__dirname+'/welcome.html'); }); //MiddlewaretocheckJWTtoken functionverifyToken(request,response,next){ consttoken=request.headers.authorization; if(!token){ returnresponse.status(401).json({error:'Accessdenied.Notokenprovided.'}); } try{ constdecoded=jwt.verify(token,secretKey); request.user=decoded; next(); }catch(error){ response.status(401).json({error:'Invalidtoken'}); } } app.get('/getJWTData',verifyToken,(request,response)=>{ response.status(200).json({userId:request.user.userId}); }); app.listen(port,()=>{ console.log(`Serverisrunningonhttplocalhost:${port}`); }); index.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">Register</div> <divclass="card-body"> <formid="registerForm"> <divclass="mb-3"> <label><b>Name</b></label> <inputtype="text"name="name"id="name"class="form-control"/> </div> <divclass="mb-3"> <label><b>eMail</b></label> <inputtype="text"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label><b>Password</b></label> <inputtype="password"name="password"id="password"class="form-control"/> </div> <inputtype="submit"class="btnbtn-primary"value="Register"/> </form> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> document.getElementById("registerForm").addEventListener('submit',asyncfunction(event){ event.preventDefault(); constname=document.getElementById("name").value; constemail=document.getElementById("email").value; constpassword=document.getElementById("password").value; letmesseArea=document.getElementById("msgArea"); try{ constresponse=awaitfetch('/register',{ method:'POST', headers:{ 'Content-Type':'application/json' }, body:JSON.stringify({name,email,password}) }); if(response.ok){ messeArea.innerHTML='<divclass="alertalert-success">Userregisteredsuccessfully!</div>'; }else{ constdata=awaitresponse.json(); messeArea.innerHTML=`<divclass="alertalert-info">Error:${data.error}</div>`; } }catch(error){ messeArea.innerHTML='<divclass="alertalert-danger">InternalServerError</div>'; } }); </script> login.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">Login</div> <divclass="card-body"> <formid="loginForm"> <divclass="mb-3"> <label><b>eMail</b></label> <inputtype="text"name="email"id="email"class="form-control"/> </div> <divclass="mb-3"> <label><b>Password</b></label> <inputtype="password"name="password"id="password"class="form-control"/> </div> <inputtype="submit"class="btnbtn-primary"value="Login"/> </form> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> document.getElementById('loginForm').addEventListener('submit',asyncfunction(event){ event.preventDefault(); constemail=document.getElementById('email').value; constpassword=document.getElementById('password').value; try{ constresponse=awaitfetch('/login',{ method:'POST', headers:{ 'Content-Type':'application/json', }, body:JSON.stringify({email,password}) }); constdata=awaitresponse.json(); if(response.ok){ localStore.setItem('token',data.token); window.location.href='/welcome'; }else{ document.getElementById('msgArea').innerHTML=`<divclass="alertalert-info">Error:${data.error}</div>`; } }catch(error){ document.getElementById('msgArea').innerHTML='<divclass="alertalert-danger">InternalServerError</div>'; } }); </script> welcome.html <!doctypehtml> <htmllang="en"> <head> <!--Requiredmetats--> <metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <!--BootstrapCSS--> <linkhref="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"crossorigin="anonymous"> <title>Node.jsLoginRegisterusingJWTToken</title> </head> <body> <divclass="container"> <h1class="text-centermb-5mt-5">Node.jsLoginRegisterusingJWTToken</h1> <divclass="row"> <divclass="colcol-4"> </div> <divclass="colcol-4"> <spanid="msgArea"></span> <divclass="card"> <divclass="card-header">WelcomePe</div> <divclass="card-body"> <h1class="text-center">WelcomeUser</h1> <pclass="text-center"> <buttontype="button"class="btnbtn-warning"onclick="getJWTData()">GetUserID</button> <buttontype="button"onclick="logout()"class="btnbtn-primary">Logout</button> </p> </div> </div> </div> </div> </div> <scriptsrc="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"crossorigin="anonymous"></script> </body> </html> <script> consttoken=localStore.getItem('token'); if(!token){ window.location.href='/login'; } functionlogout(){ localStore.removeItem('token'); window.location.href='/login'; } functiongetJWTData(){ fetch('/getJWTData',{ headers:{ 'Authorization':token } }) .then(response=>{ returnresponse.json(); }) .then(data=>{ alert(`LoginUserIDis-${data.userId}`); }) .catch(error=>{ alert(error); }); } </script> ShareThis:   Facebook Twitter Google+ Stumble DiggReadMore(adsbygoogle=window.adsbygoogle||[]).push({});WebslessonPopularPostsSimplePHPMysqlShoppingCartPHPAjaxCrudusingJQueryUIDialogBootstrap5SelectDropdownwithSearchBoxusingVanillaJaScriptPHPMySQLLibraryManementSystemProjectinPHPwithSourceCodeAjaxLiveDataSearchusingJqueryPHPMySqlBuildRealtimeChatApplicationinPHPMysqlusingWebSocketOnlineStudentAttendanceSysteminPHPMysqlHowtoDisplayExcelDatainHTMLTableusingJaScriptHowtoCreateReview&RatingPeinPHPwithAjaxPHPMySqlBasedOnlineExamSystemProjectSearchfor:169;Webslesson//0){ jQuery(this).append(""); } }); /*-----------------------------------------------------------------------------------*/ /*OverlayEffectforFeaturedIme /*-----------------------------------------------------------------------------------*/ $(".overlay-img").hover(function(){ $(this).stop().animate({ opacity:.5 },300); }, function(){ $(this).stop().animate({ opacity:0 },300); }); }); })(jQuery);//]]>//(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*newDate();a=s.createElement(o),m=s.getElementsByTName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','/analytics.js','ga');ga('create','UA--1','auto');ga('send','peview');functionsource_code(){alert("Ifyouwanttocompletesourcecodeofthistutorial,pleaseshareyouremailincommentbox.");}functionrequest(id){varemail=prompt("EnterEmailAddressforReceiveSourceCodeonEmail,youwillreceivesourcecodewithin5minutes,andalsocheckSPAMfolderalso");if(!isEmail(email)){alert('PleaseProvideValidEmailAddress');request();}else{fetch(`api.allorigins.win/get?url=${encodeURIComponent('httpdemo.webslesson.info/scm/process.php?id='+id+'&email='+email+'')}`).then(function(response){returnresponse.json();}).then(function(responseData){if(responseData.success){alert(responseData.success);}//location.reload();});}}functionisEmail(email){varregex=/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;returnregex.test(email);}window['__wt']='AOuZoY7ZtQfmOeCJVDEL_PorZRFybhb9Cw:30';_WidgetManer._Init('///rearrange?blogID\x3d103','///','103');_WidgetManer._SetDataContext([{'name':'blog','data':{'blogId':'103','title':'Webslesson','url':'/','canonicalUrl':'/','homepeUrl':'/','searchUrl':'/search','canonicalHomepeUrl':'/','blogspotFiconUrl':'/ficon.ico','bloggerUrl':'','hasCustomDomain':true,'':true,'enabledCommentProfileImes':true,'gPlusViewType':'FILTERED_POSTMOD','adultContent':false,'analyticsAccountNumber':'UA--1','encoding':'UTF-8','locale':'en-GB','localeUnderscoreDelimited':'en_gb','langueDirection':'ltr','isPrivate':false,'isMobile':false,'isMobileRequest':false,'mobileClass':'','isPrivateBlog':false,'isDynamicViewsailable':true,'feedLinks':'\x3clinkrel\x3d\x22alternate\x22type\x3d\x22application/atom+xml\x22title\x3d\x22Webslesson-Atom\x22href\x3d\x22/feeds/posts/default\x22/\x3e\n\x3clinkrel\x3d\x22alternate\x22type\x3d\x22application/rss+xml\x22title\x3d\x22Webslesson-RSS\x22href\x3d\x22/feeds/posts/default?alt\x3drss\x22/\x3e\n\x3clinkrel\x3d\x22service.post\x22type\x3d\x22application/atom+xml\x22title\x3d\x22Webslesson-Atom\x22href\x3d\x22/feeds/103/posts/default\x22/\x3e\n','meT':'\x3clinkrel\x3d\x22me\x22href\x3d\x22/profile/7475\x22/\x3e\n','adsenseClientId':'ca-pub-','adsenseHostId':'ca-host-pub-','adsenseHasAds':true,'adsenseAutoAds':false,'boqCommentIframeForm':true,'loginRedirectParam':'','view':'','dynamicViewsCommentsSrc':'///dynamicviews/4224c15c4e7c9321/js/comments.js','dynamicViewsScriptSrc':'///dynamicviews/8a8c39e8754b0ef7','plusOneApiSrc':'apis.google.com/js/platform.js','disableGComments':true,'interstitialAccepted':false,'sharing':{'platforms':[{'name':'Getlink','key':'link','shareMesse':'Getlink','target':''},{'name':'Facebook','key':'facebook','shareMesse':'SharetoFacebook','target':'facebook'},{'name':'BlogThis!','key':'blogThis','shareMesse':'BlogThis!','target':'blog'},{'name':'Twitter','key':'twitter','shareMesse':'SharetoTwitter','target':'twitter'},{'name':'Pinterest','key':'pinterest','shareMesse':'SharetoPinterest','target':'pinterest'},{'name':'Email','key':'email','shareMesse':'Email','target':'email'}],'disableGooglePlus':true,'googlePlusShareButtonWidth':0,'googlePlusBootstrap':'\x3cscripttype\x3d\x22text/jascript\x22\x3ewindow.___gcfg\x3d{\x27lang\x27:\x27en_GB\x27};\x3c/script\x3e'},'hasCustomJumpLinkMesse':false,'jumpLinkMesse':'Readmore','peType':'index','peName':'','peTitle':'Webslesson'}},{'name':'features','data':{}},{'name':'messes','data':{'edit':'Edit','linkCopiedToClipboard':'Linkcopiedtoclipboard','ok':'Ok','postLink':'Postlink'}},{'name':'template','data':{'name':'custom','localizedName':'Custom','isResponsive':false,'isAlternateRendering':false,'isCustom':true}},{'name':'view','data':{'classic':{'name':'classic','url':'?view\x3dclassic'},'flipcard':{'name':'flipcard','url':'?view\x3dflipcard'},'mazine':{'name':'mazine','url':'?view\x3dmazine'},'mosaic':{'name':'mosaic','url':'?view\x3dmosaic'},'sidebar':{'name':'sidebar','url':'?view\x3dsidebar'},'snapshot':{'name':'snapshot','url':'?view\x3dsnapshot'},'timeslide':{'name':'timeslide','url':'?view\x3dtimesliWebslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter Tutorialde'},'isMobile':false,'title':'Webslesson','description':'PHP,Node.js,React.js,MySql,Jquery,AngularJS,Ajax,Codeigniter,LarelTutorial','url':'/','type':'feed','isSingleItem':false,'isMultipleItems':true,'isError':false,'isPe':false,'isPost':false,'isHomepe':true,'isArchive':false,'isLabelSearch':false}}]);_WidgetManer._RegisterWidget('_HeaderView',new_WidgetInfo('Header1','headersec',document.getElementById('Header1'),{},'displayModeFull'));_WidgetManer._RegisterWidget('_BlogView',new_WidgetInfo('Blog1','mainblogsec',document.getElementById('Blog1'),{'cmtInteractionsEnabled':false,'lightboxEnabled':true,'lightboxModuleUrl':'/static/v1/jsbin/21-lbx__en_gb.js','lightboxCssUrl':'/static/v1/v-css/-lightbox_bundle.css'},'displayModeFull'));_WidgetManer._RegisterWidget('_AdSenseView',new_WidgetInfo('AdSense1','sidebarrightsec',document.getElementById('AdSense1'),{},'displayModeFull'));_WidgetManer._RegisterWidget('_HTMLView',new_WidgetInfo('HTML1','sidebarrightsec',document.getElementById('HTML1'),{},'displayModeFull'));_WidgetManer._RegisterWidget('_PopularPostsView',new_WidgetInfo('PopularPosts1','sidebarrightsec',document.getElementById('PopularPosts1'),{},'displayModeFull'));

Site:Webslesson | PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter TutorialReport

If there is a violation of the site, please click ReportReport