Thursday, October 22, 2020

Express Js || REST Api

 npm init 

or 
npm int -y

npm install --save express

what is nodemon 
npm install -g nodemon --save 
npm install --save-dev nodemon

I want to run nodemon server.js. 


const express = require('express');
const app =express();

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));

app.listen(port,(req, res)=>{
console.log(`Server running on port ${port}`);
})










npm install --save mongoose




const express = require('express');
const mongoose =require('mongoose');
const app =express();

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser:true});

const connection =mongoose.connection;
connection.once("open",()=>console.log('connection successfull'));

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));


app.listen(port,(req, res)=>{
    console.log(`Server running on port ${port}`);
})

................................................................................................................................................................................................................................
Example :#1 [Post Example ]

models/userSchema.js
const mongoose = require('mongoose');
const schema = mongoose.Schema;

const User = schema({
    username:{
        type: String,
        required:true,
        unique:true,
    },
    password:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    }
    })
    module.exports = mongoose.model("User", User);
....................................................................
routers/router.js
const express = require('express');
const router = express.Router();
const User = require('../model/userSchema');

router.route('/register').post((req, res)=>{
    console.log('inside user');
    const user = new User({
        username:req.body.username,
        password: req.body.password,
        email: req.body.email
    });
    user.save()
    .then(()=>{
        console.log('User Reegister Successfull');
        res.status(200).json('Okay');
    })
    .catch((error)=>{
        res.status(403).json({msg:error});
    });
   // res.json('Registered')
});


router.route("/:username").patch((req, res) => {
    User.findOneAndUpdate(
        { username: req.params.username },
        { $set: { password: req.body.password } },
        (err, result) => {
            if (err) return res.status(500).json({ msg: err });
            const msg = {
                msg: "password Successfuly updated",
                username: req.params.username,
            };
            return res.json(msg);
        })
})


router.route("/:username").delete((req, res) => {
    User.findOneAndDelete(
        { username: req.params.username },
        (err, result) => {
            if (err) return res.status(500).json({ msg: err });
            const msg = {
                msg: "User Deleted",
                username: req.params.username
            };
            return res.json(msg);
        }
    )
})


module.exports = router;
..............................................................
server.js
const express = require('express');
const mongoose =require('mongoose');
const app =express();
const userRouter = require('./routes/route');

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser:true});

const connection =mongoose.connection;
connection.once("open",()=>console.log('connection successfull'));

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));
app.use(express.json());
app.use('/user', userRouter);
app.listen(port,(req, res)=>{
    console.log(`Server running on port ${port}`);
})

....................................................................................................................................................................................................................................



....................................................................................................................................................................................................................................



No comments:

Post a Comment