Full Post Page
 

ExpressJs API With Image Crud-3

Category: NODE JS & Written by Admin On June-02-2025 21:09:41

Application Program Interface NodeJs websites Android Application __API___ MongoDB,mysql Swift iphone app API ---Data json/XML/GRAPHQL MOSTLY USE JSON IN API EXPRESSJS NodeJs API DEVELOPMENT READ app.get('/profile',(req,res)=>{}) Create app.post('/profile',(req,res)=>{}) Update app.put('/profile',(req,res)=>{}) Delete app.delete('/profile',(req,res)=>{}) notes But work with HTML use only post ,get But Show Your data Use method res.json() middleware app.use(express.json()) need command npm init -y npm install express nodemon mongoose npm install dotenv npm install multer package.js "dotenv": "^16.5.0", "express": "^5.1.0", "mongoose": "^8.15.1", "multer": "^2.0.0", "nodemon": "^3.1.10" create index.js create.models,routes folder files add in index.js const studentRouterfiles=require('./routes/students.routes') add in routes folder module.exports=router const StudentsModel=require('../models/students.model') open command mongosh show dbs ,use students-crud,show collections db.mystudentcolls.insertOne({ first_name:"sajan", last_name:'kumar', email:'sajn@admin.com', phone:"9965456564", gender:"male", profile_pic:"nodejs.png" }) open POSTMEN 1.see data all M-Get localhost:3000/api/students 2.single dat M-Get localhost:3000/api/students/683a961a0a98305151b71236 3.delete by ID method delete M-delete localhost:3000/api/students/683a961a0a98305151b71236 4. INSERT M-POSt localhost:3000/api/students/ select params-body-form-urlencoded enter key and value But with image INSERT M-POSt localhost:3000/api/students/ select params-body-form-data enter key and value 5.UPDATE M-PUT localhost:3000/api/students/683ac39fcb3f1618b4f05571 select params-body-form-urlencoded enter key and value With Image update method->put ->body->form-data->fill all data router/students.routes.js const express=require('express') // use Router method for myroutes const router=express.Router() // add Your model folder const StudentsModel=require('../models/students.model') // const { model } = require('mongoose') //inbulit package fs for delete files iamge const fs =require('fs') // image package const multer=require('multer') const path=require('path') const storage= multer.diskStorage({ destination:(req, file, cb) => { cb(null, './uploads') }, filename:(req,file,cb)=>{ const newFileName = Date.now() + path.extname(file.originalname) cb(null ,newFileName) } }) const fileFilter=(req,file,cb)=>{ if(file.mimetype.startsWith('image/')){ cb(null,true) }else{ cb(new Error('Only image are allowed'),false) } } const upload=multer({ storage:storage, fileFilter:fileFilter, limit:{ fileSize:1024 * 1024 * 3 } }) // 1. See All data router.get('/',async(req,res)=>{ try{ const students_fetchall=await StudentsModel.find() res.json(students_fetchall) }catch(err){ res.status(500).json({message:err.message}) } }) // 3. See single data router.get('/:id',async(req,res)=>{ try{ const students_singledata=await StudentsModel.findById(req.params.id) // id se value lene ke lie req,params.id use krte h //before check data come or not may be id wrong if(!students_singledata) return res.status(404).json({message:'students not found'}) res.json(students_singledata) }catch(err){ res.status(500).json({message:err.message}) } }) // 2. add new data with image router.post('/',upload.single('profile_pic'),async(req,res)=>{ try{ // const newStudent=await StudentsModel.create(req.body) // image add const newStudentALL=new StudentsModel(req.body) if(req.file){ newStudentALL.profile_pic=req.file.filename } const newStudent =await newStudentALL.save() //end image res.status(201).json(newStudent) }catch(err){ res.status(400).json({message:err.message}) } }) // 4. update All data // { new: true} para latest value show krta h router.put('/:id',upload.single('profile_pic') ,async(req,res)=>{ try{ const existingStudent=await StudentsModel.findById(req.params.id) //update recored ko update krne pr image n hoga upload if(!existingStudent) { if(req.file.filename) { const filepath=path.join('./uploads',req.file.filename) fs.unlink(filepath,(err)=>{ if(err) console.log('Failed to Delete image:',err) }) // end update recored ko update krne pr image n hoga upload } return res.status(404).json({message:'students not found'}) } if(req.file){ if(existingStudent.profile_pic ){ const oldimagepPath=path.join('./uploads',existingStudent.profile_pic) fs.unlink(oldimagepPath,(err)=>{ if(err) console.log('Failed to Delete old image:',err) }) } req.body.profile_pic=req.file.filename } const updateStudent=await StudentsModel.findByIdAndUpdate(req.params.id,req.body,{ new: true}) res.json(updateStudent) }catch(err){ res.status(500).json({message:err.message}) } }) // 5. Delete data with folder image router.delete('/:id',async(req,res)=>{ try{ const delstudent=await StudentsModel.findByIdAndDelete(req.params.id) if(!delstudent) return res.status(404).json({message:'students not found'}) //image delete if(delstudent.profile_pic){ const filePath=path.join('./uploads',delstudent.profile_pic) fs.unlink(filePath,(err)=>{ if(err) console.log('Failed to Delete:',err) }) } res.json( {message:'student Deleted'}) }catch(err){ res.status(500).json({message:err.message}) } }) //module export route in index.js files and import in index.js module.exports=router

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