Handling Get Request in REST API using nodejs and mongoDB
Read data using Get request
app.get("/students", async (req, res)=>{try{const studentdata = await Student.find();res.send(studentdata);}catch(e){console.log(e);}})
app.get("/students/:id", async (req, res)=>{try{const _id = req.params.id;// console.log(req.params.id);// res.send(req.params.id);const studentData = await Student.findById(_id);if(!studentData){return res.status(404).send();}else{res.send(studentData);}}catch(e){console.log(e);}})
full source code app.js
const express = require("express");require("./db/conn");const Student = require("./models/students");const app = express();const port = process.env.PORT || 8000;// use express.jsonapp.use(express.json());// define rootapp.get("/",(req, res)=>{res.send("home page")})// create// app.post("/students",(req,res)=>{// console.log(req.body);// const user = new Student(req.body);// user.save().then(()=>{// res.status(201).send(user)// }).catch((e)=>{// res.status(400).send(e);// }),// async functionapp.post("/students", async(req, res)=>{try{const user = new Student(req.body);const result = await user.save();res.status(201).send(result)}catch{res.status(400).send(e);}})// read the data of registrered studentapp.get("/students", async (req, res)=>{try{const studentdata = await Student.find();res.send(studentdata);}catch(e){console.log(e);}})// get the individual student data using id//app.get("/students/:id", async (req, res)=>{try{const _id = req.params.id;// console.log(req.params.id);// res.send(req.params.id);const studentData = await Student.findById(_id);if(!studentData){return res.status(404).send();}else{res.send(studentData);}}catch(e){console.log(e);}})app.listen(port, ()=>{console.log(`connecting port ${port}`)});
Post a Comment