MERN App

rest api react node mongo express

front end

App.js

import React from 'react';
import "bootstrap/dist/css/bootstrap.min.css"
import {BrowserRouter as Router,Route,Link} from "react-router-dom";import './App.css';import ViewCourse from "./Component/viewCourse";import EditCourse from "./Component/editCourse";import AddCourse from "./Component/addCourse";import DeleteCourse from "./Component/deleteCourse";
class App extends React.Component{



    render() {
        return (
            <div style={{background:'grey' , height:'752px', position:'relative'}}>            <Router>            <div className="App" ><br/>                <h1>Online Course</h1>                                <Link to="/">Courses</Link>                <Link to="/create">Add Course</Link>
                <Route path="/" exact component={ViewCourse}/>                <Route path="/edit/:id" component={EditCourse}/>                <Route path="/create" component={AddCourse}/>                <Route path="/delete/:id" component={DeleteCourse}/>
            </div>            </Router>            </div>        );    }
}

export default App;


Components

Add

import React, {Component} from 'react';import 'bootstrap/dist/css/bootstrap-grid.min.css';import axios from 'axios';

export default class addCourse extends React.Component{

    constructor(props){
        super(props);
        this.changeCourseName = this.changeCourseName.bind(this);        this.changeCourseId= this.changeCourseId.bind(this);        this.changeCourseDet= this.changeCourseDet.bind(this);        this.changeCourseFee= this.changeCourseFee.bind(this);        this.onSubmit = this.onSubmit.bind(this);
        this.state={
            CourseName:'',            CourseId:'',            CourseDet:'',            CourseFee:'',            completed:false
        }
    }
    changeCourseName(e){
        this.setState({
            CourseName: e.target.value        });    }

    changeCourseId(e){
        this.setState({
            CourseId: e.target.value        });    }
    changeCourseDet(e){
        this.setState({
            CourseDet:e.target.value        });    }

    changeCourseFee(e){
        this.setState({
           CourseFee:e.target.value        });    }

    onSubmit(e) {
        e.preventDefault();
        console.log(`Form submitted:`);        console.log(`Course Name :${this.state.CourseName}`);        console.log(`Course Id :${this.state.CourseId}`);        console.log(`Course Details :${this.state.CourseDet}`);        console.log(`Course Fee :${this.state.CourseFee}`);        console.log(`Course Fee :${this.state.completed}`);
        const newCourse={
            CourseName:this.state.CourseName,            CourseId:this.state.CourseId,            CourseDet:this.state.CourseDet,            CourseFee:this.state.CourseFee,            completed:this.state.completed
        }
        axios.post('http://localhost:4000/course/add',newCourse)
            .then(res => console.log(res.data));

        this.setState({
            CourseName:'',            CourseId:'',            CourseDet:'',            CourseFee:'',            completed:false        })
    }




    render(){
        return(
            <div style={{background:'grey'}}>
            <div style={{background:'url(https://images.unsplash.com/photo-1516617442634-75371039cb3a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80) center/cover' , marginTop:'40px', marginLeft:'500px', marginRight:'500px' , padding:'20px'}}>              <pre>  <h2 style={{color:'white'}}>Add course</h2>                <form onSubmit={this.onSubmit} ><div>                    <div className="form-group" align="left">                    <label style={{color:'white'}}>Course Name: </label>                        <input type="text"                           className="form-control"                    value={this.state.CourseName}
                           onChange={this.changeCourseName}
                    /><br/></div>                    <div className="form-group" align="left">                    <label style={{color:'white'}}>Course Id: </label>                    <input type="text"                           className="form-control"                           value={this.state.CourseId}
                           onChange={this.changeCourseId}
                    /><br/></div>                    <div className="form-group" align="left">                    <label style={{color:'white'}}>Course Details: </label>                    <input type="text"                           className="form-control"                           value={this.state.CourseDet}
                           onChange={this.changeCourseDet}
                    /><br/></div>                    <div className="form-group" align="left">                    <label style={{color:'white'}}>Course Fee: </label>                    <input type="text"                           className="form-control"                           value={this.state.CourseFee}
                           onChange={this.changeCourseFee}
                    /><br/></div>                    <div>
                        <input type="submit" value="Create Course" className="btn btn-primary"/></div></div>                </form></pre>            </div>            </div>        );    }
}




delete

import React from 'react';import axios from 'axios';
export default class PersonList extends React.Component {

    constructor(props){
        super(props);

        this.state ={
            id: '',
        }
    }

    componentDidMount() {
        axios.get('http://localhost:4000/course/'+this.props.match.params.id)
            .then(response =>{


                this.setState({
                    id: response.data._id,                })
            })
            .catch(function (error) {
                console.log(error)
            })
    }


    handleChange (event) {
        this.setState({
            id: event.target.value });    };


    handleSubmit = event => {
        event.preventDefault();
        axios.delete(`http://localhost:4000/course/delete/${this.state.id}`)
            .then(res => {
                console.log(res);                console.log(res.data);            });        this.props.history.push('/');    };

    render() {
        return (
            <div>                <form onSubmit={this.handleSubmit}>                    <label>                        Course ID:
                        <input type="text" name="id" onChange={this.handleChange} value={this.state.id}/>                    </label>                    <button type="submit">Delete</button>                </form>            </div>        )
    }
}


edit
import React, {Component} from 'react';import axios from 'axios';

export default class editCourse extends React.Component{
    constructor(props){
        super(props);
        this.changeCourseName = this.changeCourseName.bind(this);        this.changeCourseId= this.changeCourseId.bind(this);        this.changeCourseDet= this.changeCourseDet.bind(this);        this.changeCourseFee= this.changeCourseFee.bind(this);        this.onSubmit = this.onSubmit.bind(this);
        this.state ={
            CourseName:'',            CourseId:'',            CourseDet:'',            CourseFee:'',            completed:false        }
    }


    componentDidMount() {
        axios.get('http://localhost:4000/course/'+this.props.match.params.id)
            .then(response =>{


                this.setState({
                    CourseName: response.data.CourseName,                    CourseId: response.data.CourseId,                    CourseDet: response.data.CourseDet,                    CourseFee: response.data.CourseFee,                    completed:response.data.completed

                })
            })
            .catch(function (error) {
                console.log(error)
            })
    }

    changeCourseName(e){
        this.setState({
            CourseName: e.target.value        });    }

    changeCourseId(e){
        this.setState({
            CourseId: e.target.value        });    }
    changeCourseDet(e){
        this.setState({
            CourseDet:e.target.value        });    }

    changeCourseFee(e){
        this.setState({
            CourseFee:e.target.value        });    }

    onSubmit(e) {
        e.preventDefault();

        const obj={
            CourseName:this.state.CourseName,            CourseId:this.state.CourseId,            CourseDet:this.state.CourseDet,            CourseFee:this.state.CourseFee,            completed:this.state.completed
        }
        axios.post('http://localhost:4000/course/update/'+this.props.match.params.id,obj)
            .then(res => console.log(res.data));
        this.props.history.push('/');
    }

    delete(e){
        e.preventDefault();        axios.delete('http://localhost:4000/course/delete/'+this.props.match.params.id)
            .then(res=>console.log(res.data))

    }

    render() {
        return(
            <div>                <h2>Edit course</h2>                <form onSubmit={this.onSubmit} >                    <div className="form-group">                        <label>Course Name</label>                        <input type="text"                                className="form-control"                                value={this.state.CourseName}
                                onChange={this.changeCourseName}
                        />                    </div>                    <div className="form-group">                        <label>Course Id</label>                        <input type="text"                               className="form-control"                               value={this.state.CourseId}
                               onChange={this.changeCourseId}
                        />                    </div>                    <div className="form-group">                        <label>Course Details</label>                        <input type="text"                               className="form-control"                               value={this.state.CourseDet}
                               onChange={this.changeCourseDet}
                        />                    </div>                    <div className="form-group">                        <label>Course Fee</label>                        <input type="text"                               className="form-control"                               value={this.state.CourseFee}
                               onChange={this.changeCourseFee}
                        />                    </div>                    <div className="form-group">                        <input type="submit"                               className="btn btn-primary"                               value="Update Course"
                        />                    </div>                </form>
            </div>        )
    }
}

view

import React, {Component} from 'react';import {Link} from 'react-router-dom';import axios from 'axios';


const Course = props =>(
    <tr>
        <td>{props.course.CourseName}</td>        <td className={props.course.completed ? 'completed':''}>{props.course.CourseId}</td>        <td className={props.course.completed ? 'completed':''}>{props.course.CourseDet}</td>        <td className={props.course.completed ? 'completed':''}>{props.course.CourseFee}</td>        <td>            <Link to={"/edit/"+props.course._id}>Edit</Link>&nbsp;&nbsp;&nbsp;            <Link to={"/delete/"+props.course._id}>Delete</Link>
        </td>
    </tr>);
export default class viewCourse extends React.Component{

    constructor(props){
        super(props);        this.state = {courses:[]};    }

    componentDidMount(){
        axios.get('http://localhost:4000/course/')
            .then(response=>{
                this.setState({courses:response.data})
            })
            .catch((error)=>{
                console.log(error)
            })
    }

    componentDidUpdate() {
        axios.get('http://localhost:4000/course/')
            .then(response=>{
                this.setState({courses:response.data})
            })
            .catch((error)=>{
                console.log(error)
            })
    }


    courseList(){
        return this.state.courses.map((currentCourse,i) =>{
            return <Course course={currentCourse} key={i}/>;        });    }



    // delete(e){    //     e.preventDefault();    //     axios.delete('http://localhost:4000/course/delete/'+this.props.course._id)    //         .then(res=>console.log(res.data))    //    // }    //    // deleteCourse(courseId){    //     const {courses}=this.state;    //     this.setState({    //         courses:courses.filter(course => this.props.course._id !== courseId)    //     })    //    // }    // onDelete(){    //     let courseId=this.props.courses.id;    //     axios.delete(`http://localhost:4000/course/delete/${courseId}`)    //         .then(response =>{    //             this.props.history.push('/');    //         }).catch(err=>console.log(err));    // }

    render() {
        return(
            <div>                <h2>View Course</h2>                <table className="table table-striped" style={{marginTop:20}}>                    <thead>                    <tr>                        <th>Course Name</th>                        <th>Course ID</th>                        <th>Course Description</th>                        <th>Course Fee</th>                        <th>Edit  &nbsp; Delete</th>


                    </tr>                    </thead>
                    <tbody>                    {this.courseList()}
                    </tbody>                </table>            </div>        )
    }
}

backend

server

const express = require('express');const app = express();const bodyParser = require('body-parser');const cors = require('cors');const crsRoutes = express.Router();const PORT = 4000;
let Course = require('./model');
//connect mongodbconst mongoose = require('mongoose');

app.use(cors());app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/course,',{useNewUrlParser: true});const connection =mongoose.connection;connection.once('open', check=> {
   console.log('mongoDB connect Successfully');});
crsRoutes.route('/').get((req,res)=>{
    Course.find((err,courses)=>{
        if (err){
            console.log(err);        } else {
            res.json(courses)
        }
    });});
crsRoutes.route('/:id').get((req,res)=>{
    let id = req.params.id;    Course.findById(id,(err,courses)=>{
        res.json(courses);    })
});crsRoutes.route('/add').post((req,res)=>{
    let course = new Course(req.body);    course.save()
        .then(course=>{
            res.status(200).json({'course':'course added successfully'});        })
        .catch(err=>{
            res.status(400).send('adding failed');        })
});
crsRoutes.route('/update/:id').post(function (req,res) {
   Course.findById(req.params.id,function (err, course) {
       if (!course)
           res.status(404).send('data is not found');       else {
           course.CourseName = req.body.CourseName;           course.CourseId = req.body.CourseId;           course.CourseDet = req.body.CourseDet;           course.CourseFee = req.body.CourseFee;           course.completed = req.body.completed;
           course.save().then(course => {
               res.json('Course Updated');           })
               .catch(err => {
                   res.status(400).send("Update not possible")
               })
       }
   })
});

// crsRoutes.put('update/:id',(req,res)=>{//    Course.findByIdAndUpdate({_id: req.params.id},req.body).then(function () {//        Course.findOne({_id: req.params.id}).then( (course)=> {//            res.send(course);//        });//    } );// });
crsRoutes.delete('/delete/:id',(req,res)=>{
    Course.findByIdAndRemove({_id:req.params.id}).then(course=>{
        res.send(course);
    })
});
app.use('/course',crsRoutes);
app.listen(PORT, err => {
    if (err){
        console.error(err);        return;    }
    console.log("Server is running on Port : "+PORT);
});


model

const mongoose = require('mongoose');const Schema = mongoose.Schema;
let Course = new Schema({
    CourseName:{
        type:String
    },    CourseId:{
        type:String
    },    CourseDet:{
        type:String
    },
    CourseFee:{
        type:String
    },    completed:{
        type:Boolean
    }

});
module.exports = mongoose.model('Course',Course);


add dropdown list

import React, { Component } from 'react';import { BrowserRouter as Router, Route, Link } from 'react-router-dom';import axios from 'axios';import Select from 'react-select';

export default class AddBook extends Component {

    constructor(props) {
        super(props);
        this.onChangeName = this.onChangeName.bind(this);        this.onChangeISBN = this.onChangeISBN.bind(this);        this.onChangeAuthor = this.onChangeAuthor.bind(this);        this.onChangePrice = this.onChangePrice.bind(this);        this.onChangeYear = this.onChangeYear.bind(this);        this.onChangePublisher = this.onChangePublisher.bind(this);
        // this.showDrop = this.showDrop.bind(this);        // this.hideDrop = this.hideDrop(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',            isbn: '',            author: '',            price: '',            year: '',            publisher: '',            authors: [],            authorId: ''        }

    }

    onChangeName(e) {
        this.setState({
            name: e.target.value        });    }

    onChangeISBN(e) {
        this.setState({
            isbn: e.target.value        });    }

    onChangeAuthor(optionSelected) {

        const name = this.name;        const value = optionSelected.value;        const label = optionSelected.label;
        console.log(name);        console.log(value);        console.log(label);
        this.setState({
            author: label,            authorId: value
        });
        console.log(this.state.author);
    }

    onChangePrice(e) {
        this.setState({
            price: e.target.value        });    }

    onChangeYear(e) {
        this.setState({
            year: e.target.value        });    }

    onChangePublisher(e) {
        this.setState({
            publisher: e.target.value        });    }



    componentDidMount() {

        axios.get('http://localhost:3000/api/author/all')
            .then(response => {
                console.log(response);
                const authorList = [];
                for (var i = 0; i < response.data.authors.length; i++) {
                    const obj = {
                        label: response.data.authors[i].firstName + " " + response.data.authors[i].lastName,                        value: response.data.authors[i]._id                    }

                    authorList.push(obj);                }


                this.setState({
                    authors: authorList
                });


            }).catch(err => {
                console.log(err);            });

    }



    onSubmit(e) {
        e.preventDefault();

        console.log(this.state.author);

        const book = {
            name: this.state.name,            isbn: this.state.isbn,            author: this.state.authorId,            price: this.state.price,            year: this.state.year,            publisher: this.state.publisher
        }


        axios.post('http://localhost:3000/api/book/add', book)
            .then(response => {

                console.log(response);                this.props.history.push('/');            }).catch(err => {
                console.log(err);            });    }





    render() {
        return (

            <div>
                <h3>Add Book</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Book Name:</label>                        <input type="text" className="form-control"                            value={this.state.name}
                            onChange={this.onChangeName}
                        />                    </div>

                    <div className="form-group">
                        <label>ISBN:</label>                        <input type="text" className="form-control"                            value={this.state.isbn}
                            onChange={this.onChangeISBN}
                        />                    </div>

                    <div className="form-group">
                        <label>Author:</label>
                        <Select options={this.state.authors} onChange={this.onChangeAuthor} />                    </div>


                    <div className="form-group">
                        <label>Price:</label>                        <input type="text" className="form-control"                            value={this.state.price}
                            onChange={this.onChangePrice}
                        />                    </div>
                    <div className="form-group">
                        <label>Year:</label>                        <input type="text" className="form-control"                            value={this.state.year}
                            onChange={this.onChangeYear}
                        />                    </div>

                    <div className="form-group">
                        <label>Publisher:</label>                        <input type="text" className="form-control"                            value={this.state.publisher}
                            onChange={this.onChangePublisher}
                        />                    </div>
                    <div className="form-group">                        <input type="submit" value="Add Book" className="btn btn-primary" />                    </div>



                </form>
            </div>


        );    }





}









see you in next blog

thank you









































Comments

Popular posts from this blog

Node Introduction

React installation