Home > OS >  Is there an erorr in connection class in koa?
Is there an erorr in connection class in koa?

Time:06-28

this is the backend i created for react koa app. post, get, delete methods are working. lets check is it the correct format ?

I used koajs for backend reactjs for frontend and mongodb for database connection

    const {MongoClient} = require("mongodb");

const client = new MongoClient('mongodb://localhost:27017', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

client.connect(err => {
    if(err){
        console.error(err);
        process.exit(-1);
    }
    console.log("Successfully connected to MongoDB");
})

module.exports = client;

CodePudding user response:

server.js

    const  Koa = require('koa');
    
    const bodyParser = require('koa-bodyParser');
    const cors = require('@koa/cors');
    
    
    
    const productRoutes = require('./routes/ProductRoutes');
    const UserRoutes = require('./routes/UserRoutes');
    const app = new Koa();
    
    app.use(cors({
        origin: "http://localhost:1234",
        
    }
      
    ));
app.use(bodyParser());


app.use(productRoutes.routes()).use(productRoutes.allowedMethods());
app.use(UserRoutes.routes()).use(UserRoutes.allowedMethods());

//setup connection 

app.listen(3000);
console.log("application is running on port 3000")

routes

const Router = require("@koa/router");

const { removeProductID,UpdateProduct, GetAll, createProduct, getProductID} = require ("../api/Product.api");


//define perfix
const router = new Router({
    prefix:'/products'
})
//get all products

router.get('/all', async ctx=>{

    ctx.body = await GetAll();

})

//add product

router.post('/add', async ctx=>{

    let product = ctx.request.body;
    product = await createProduct(product);

    ctx.response.status = 200;
    ctx.body = product;

})


//get item by id
router.get('/:id' , async ctx=>{

    const id =  ctx.params.id;
    ctx.body = await getProductID(id);

} )

//delete product
router.delete('/:id' , async ctx=>{

    const id = ctx.params.id;
    await removeProductID(id);
    ctx.response.status = 200;
    
})


//update

router.put('/:id' , async ctx=>{

    const id = ctx.params.id;
    let product = ctx.request.body;

    product = await UpdateProduct(id,product);
    ctx.response.status = 200;
    ctx.body = product;


})

module.exports = router;



const Router = require("@koa/router");
const {loginUsers,getAllUsersList,RegisterUser} = require("../api/UserApi");


//perfix

const router = new Router({
    prefix:"/user"
})


//create user

router.post("/register" , async(ctx)=>{

    let data = ctx.request.body;
    var user = await RegisterUser(data);

    ctx.response.status = 200;
    ctx.body=user
})

//get all users
router.get("/getAllUsers" , async(ctx)=>{
    ctx.body= await getAllUsersList();
})

//login

router.post('/login' , async(ctx)=>{
    let data = ctx.request.body;
    let logins = await loginUsers(data);

    ctx.response.status = 200;
    ctx.body=logins;
})

//delete account 
//router.delete("/remove-User/:id" , async(ctx)=>{
 //   const id  = ctx.params.id;
 //   var data = await del
//})



module.exports = router;

model

const {MongoClient} = require("mongodb");

const client = new MongoClient('mongodb://localhost:27017', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

client.connect(err => {
    if(err){
        console.error(err);
        process.exit(-1);
    }
    console.log("Successfully connected to MongoDB");
})

module.exports = client;



const product = require('./Connection').db('store1').collection('productaa');

//object id access to the document based on the _id
const ObjectId = require('mongodb').ObjectId;


//create

const create = async ({name, price, description})=>{

    const result  = await product.insertOne({name , price,description});
    return result.ops[0];

}

//read all 

const GetAllProduct = async () =>{

    const pro = await product.find();
    return pro.toArray();

}

//read product by id 

const getProductByID = async(id)=>{

    return await product.findOne({_id:ObjectId(id)});
}


//update

const editProduct = async (id, {name ,price, description})=>{

    console.log(id);

    const result  = await product.replaceOne({_id:ObjectId(id)},
    {name , price, description});
    return result.ops[0];
    

}

//remove product

const removeByID = async id =>{
    await product.deleteOne({_id:ObjectId(id)});
}

module.exports = {removeByID,editProduct,getProductByID,GetAllProduct,create}





const User = require("./Connection").db("users").collection("userdetails");

const ObjectID = require('mongodb').objectId;


//create user
const createUser = async({name , email, passowrd , userRole})=>{

    const result = await User.insertOne({name,email,passowrd,userRole});
    return result;
}


//get all users 
const getAllUsers  = async () =>{
    const data = await User.find();
    return data.toArray();
}



//login

const Login = async({email, passowrd})=>{
    const user = await User.findOne({"email":email});
    if(user){
        if(user?.passowrd !==passowrd){
            return {msg:'login faild'}

        }
        else{
            return {msg:"login ok" , token:user._id , userRole:user.userRole}
        }
    }
    else{
        return {msg:"login faild"}
    }
}

module.exports = {Login,createUser,getAllUsers}

api

//import  methods in dal 
const  {removeByID,editProduct,getProductByID,GetAllProduct,create} = require("../dal/Products.dao")


//map create method

const createProduct = async({name , description, price})=>{

    //create object
    const product ={
        name , 
        description, 
        price

    }
    return await create(product);
}


//get all methods 
const GetAll = async ()=>{
return await GetAllProduct();
}


//get by id

const getProductID = async id=>{
return await getProductByID(id);
}


//delete product
const removeProductID = async id =>{
    
return await removeByID(id);
}

//update 
const UpdateProduct = async(id,{name , description, price})=>{

    return await editProduct(id,{name , description, price});
}


//export to routes
module.exports={
    removeProductID, 
    UpdateProduct,
    GetAll,
    createProduct,
    getProductID

}





const {Login,createUser,getAllUsers} = require('../dal/User');


//user create
const RegisterUser = async (data)=>{

    const user={
        name:data.name,
        email:data.email,
        passowrd:data.passowrd,
        userRole:data.userRole,
    }
    return await createUser(user);
}

//get all users 

const getAllUsersList = async()=>{

    return  await getAllUsers();
}

//login

const loginUsers = async(data)=>{

    const createUser={
        email:data.email,
        passowrd:data.passowrd
    }
    return await Login(createUser);
}

module.exports = {loginUsers,getAllUsersList,RegisterUser}

CodePudding user response:

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
 const AllProdcut = () => {

    const [product, setproduct] = useState();
    const [serachItem,setserachItem] =useState([]);


    useEffect(async () => {
        try {
          const data = await (
          await axios.get("http://localhost:3000/products/all")
          ).data;
          setproduct(data);
        
        } catch (error) {
          console.log(error);
      
        }
      }, []);

      function deleteProduct(_id) {
        axios
          .delete("http://localhost:3000/products/"   _id)
          .then((res) => {
            console.log(res.data);
    
            alert(" deleted");
          })
          .catch((err) => {
            alert(err);
          });
    
          setproduct(product.filter((product) => product._id !== _id));
      }


  return (

    <div className="container">
        
        <br></br>  <br></br>  <br></br>

        <Link  to="/CreateProduct">
        <button type="submit" className="btn btn-primary">Add new Product
                            </button>
</Link>

<br></br>  <br></br>  

<div className="col-md-9">
  <h4> Now You Can Search  </h4>
  <input type="search"  placeholder="Search by id  " aria-label="Search"  onChange={event=>{setserachItem(event.target.value)}} 
    aria-describedby="search-addon" />
  </div><br></br>


        <table className="table table-dark">
    <thead className="">
      <tr>
        <th> ID</th>
        <th>name</th>
        <th>price  </th>
        <th>Description</th>
        <th>update</th>
        <th>delete</th>
      </tr>
    </thead>

    <tbody>
      {product &&
        product.map((product) => {
          if(serachItem ==""){
            return product
          }else if(product.name.toLowerCase().includes(serachItem.toLowerCase())){
            
            return product
          }})
.map((product)=>{
          return (
            <tr>
              <td>{product._id}</td>
              <td>{product.name}</td>
              <td>{product.description}</td>
              <td>{product.price}</td>
              
              <td>
                       <a
                                        className="btn btn-warning"
                                        href={`/products/${product._id}`} >
                                        &nbsp;&nbsp; Update
                      </a>

                                </td>

                                <td>
                                    <a
                                        className="btn btn-warning"
                                        onClick={() => {
                                          
                                            deleteProduct(product._id);
                                        }}
                                    >
                      
                                        &nbsp;&nbsp; delete
                      </a>

                                </td>

            </tr>
          );
        })}
    </tbody>
  </table></div>
  );


}





export default AllProdcut;




import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";


const CreateProduct = () => {


    const [Product, setProduct] = useState({
        name:'',
        price:"",
        description:"",
    });
  
    let navigate = useNavigate();

    function sendData(e) {

        e.preventDefault();

        axios
            .post("http://localhost:3000/products/add", Product)
            .then(() => {

                alert("New product  Created");
                navigate("/");
            })
            .catch((err) => {
                alert(err);
            });

            setProduct({
                name: "",
                price: "",
                description: "",
             
            });
        }

        function handleChange(event) {
            const { name, value } = event.target;
    
            setProduct((preValue) => {
                return {
                    ...preValue,
                    [name]: value,
                };
            });
        }



  return (

    <div className='container'>

<form onSubmit={sendData}>
<h1>Add new  product</h1>
                    <div className="form-group row">
                        
                        <label for="name" className="col-sm-3 col-form-label">
                            product Name
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id=""
                                name="name"
                                placeholder="Enter product Name"
                                onChange={handleChange}
                                value={Product.name}
                             
                            />
                        </div>
                    </div>
                    <div className="form-group row">
                        <label for="leaderITNum" className="col-sm-3 col-form-label">
                        price
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id="price"
                                name="price"
                                placeholder="Enter price"
                                onChange={handleChange}
                                value={Product.price}
                                required
                            />
                        </div>
                    </div>
                    <div className="form-group row">
                        <label for="topicName" className="col-sm-3 col-form-label">
                            Product description 
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id="description"
                                name="description"
                                placeholder="Enter description"
                                onChange={handleChange}
                                value={Product.description}
                                required
                            />
                        </div>
                    </div>

                   

                    <div className="form-group row">
                        <div className="col-sm-10">
                            <button type="submit" className="btn btn-primary">
                                <b >Add Product</b>
                            </button>

                        </div>
                    </div>
                </form>


    </div>
  )
}






export default CreateProduct


import React ,{useEffect , useState} from "react";
import { useNavigate } from "react-router-dom";

import { loginFunction } from "../services/LoginServices";


const Login9 = () => {

    const navigate = useNavigate();

    const [fromdata, setFromtdata] = useState({

        email:"",
        passowrd:''

    });


    const {email , passowrd} = fromdata;

    const OnChangeData = (e) =>{
        setFromtdata({ ...fromdata, [e.target.name]: e.target.value });
    }


    const submitdata = async (e)=>{
        e.preventDefault();
        console.log("data",fromdata);

        let data = await loginFunction(fromdata);
        console.log("data",data);

        if(data?.data?.token){
            localStorage.setItem("token",data?.data?.token);
            localStorage.setItem("userRole",data?.data?.userRole);
            navigate("/main");
        }
        else{
            alert("faild");
        }
    }

    





  return (


    <div><div>
    <center>
        <div>
            <h2>Login to the system</h2>                    
        </div>
        <br /><br />
        <div>
            <form className="form">
                <input 
                type="email"
                placeholder="Enter your email"
                name="email"
                value={email}
                onChange={(e)=>OnChangeData(e)}
                />
                <br/>
                <br/>

                <input 
                type="password"
                placeholder="Enter your password"
                name="passowrd"
                value={passowrd}
                onChange={(e)=>OnChangeData(e)}
                />
                <br/>
                <br/>

                <button className="btn btn-success" onClick={(e)=>submitdata(e)}>Login9</button>

            </form>
        </div>
        <br/>
        <h4>Don't Have an account? Register Below</h4>
        <a href="/RegisterUser" className="btn btn-primary">Register</a>
    </center>
    </div></div>
  )
}

export default Login9

import React,{useEffect,useState} from "react";
import { useNavigate} from "react-router-dom";


const Navbar = () => {


    const navigate = useNavigate();
    const [userRole, setuserRole] = useState("")


    useEffect(() => {
        setuserRole(localStorage.getItem("userRole"));
    }, [])


    useEffect(() => {
        console.log("userRole",userRole);
    }, [userRole])



    const handleSubmit = () => {
        localStorage.removeItem("token");
        localStorage.removeItem("userRole");
        navigate("/");
   
      }


  return (
    <div> <div>
    <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
  <div className="container-fluid">
    <a className="navbar-brand" href="/">Home</a>
    <div className="collapse navbar-collapse" >
      <div className="navbar-nav">

        <a style={{ display: userRole == "admin" ? "flex" : "none" , textDecoration:"none"}} className="sidebarListItem" aria-current="page" href="/">Admin Pages</a>
        
        <a style={{ display: userRole == "student" ? "flex" : "none" , textDecoration:"none"}} className="sidebarListItem" href="/" aria-current="page">Student Pages</a>



      </div>
    </div>
  </div>  
  <button onClick={handleSubmit} className="btn btn-primary" type="submit" style={{ float: "right", marginRight: "10px" , display:userRole ? "flex":"none"}}>
    {"Logout"}
  </button>
</nav>
    </div></div>
  )
}

export default Navbar;



import React,{useEffect, useState} from "react";
import { useNavigate } from "react-router-dom";
import { RegisterUsers } from "../services/LoginServices";


const RegisterUser = () => {


    const navigate = useNavigate();

    const [formdata, setformdata] = useState({
        name:"",
        email:"",
        passowrd:"",
        userRole:""
    });


    const {name,email,passowrd,userRole} = formdata;

    const onChangedata = (e) =>{
        setformdata({ ...formdata, [e.target.name]: e.target.value });
    }



    const AddNewUser = async (e)=>{
        e.preventDefault();
        try {
            var data = await RegisterUsers(formdata);
            console.log(data);
            if(data?.data?.name)
            {
                alert("Register success");
                navigate("/")
            }
            else
            {
                navigate("/main")                
            }
        } catch (error) {
            console.log(error);
        }

    }


  return (


    <div> <div>
    <center>
        <div>
            <h2>Register</h2>                    
        </div>
        <br /><br />
        <div>
            <form className="form">
                <input 
                type="text"
                placeholder="Enter your name"
                name="name"
                value={name}
                onChange={(e)=>onChangedata(e)}
                />
                <br/>
                <br/>

                <input 
                type="email"
                placeholder="Enter your email"
                name="email"
                value={email}
                onChange={(e)=>onChangedata(e)}
                />
                <br/>
                <br/>

                <input 
                type="password"
                placeholder="Enter your password"
                name="passowrd"
                value={passowrd}
                onChange={(e)=>onChangedata(e)}
                />
                <br/>
                <br/>

                <label>select user role</label>
                <br/>
                <select >
  <option      onChange={(e)=>onChangedata(e)}  name="userRole" selected>Open this select </option>
  <option value="customer">customer</option>
  <option value="admin">admin</option>

</select>
          
                <br/>
                <br/>

                <button className="btn btn-dark" onClick={(e)=>AddNewUser(e)}>Insert</button>
                <br></br>
                <h4> Have an account?  </h4>
        <a href="/" className="btn btn-dark">login</a>
            </form>
        </div>
    </center>
    </div></div>
  )
}

export default RegisterUser





import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { useParams } from "react-router";

const UpdateProduct = () => {


  const [Product, setProduct] = useState({
      name:'',
      price:"",
      description:"",
  });

  let navigate = useNavigate();
  const  {id} = useParams();



  useEffect(() => {

    function getProduct() {
        axios
            .get(`http://localhost:3000/products/${id}`)
            .then((res) => {
                setProduct(res.data);
            })
            .catch((err) => {
                alert(err.message);
            });
    }
    getProduct();
}, []);



function  sendData(e){

    e.preventDefault();

    const UpdateProduct = Product;

    axios.put(`http://localhost:3000/products/${id}`,UpdateProduct)
    .then(() => {

        alert("updated success");
        navigate("/");
    })

    .catch((err) => {
        alert(err);
    });
}

function handleChange(event) {
    const { name, value } = event.target;

    setProduct((preValue) => {
        return {
            ...preValue,
            [name]: value,
        };
    });
}


  return (


    <div className="container">

<br></br><br></br><br></br><br></br><br></br><br></br>


<form onSubmit={sendData}>
<h1>update product</h1>
                    <div className="form-group row">
                        
                        <label for="name" className="col-sm-3 col-form-label">
                            product Name
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id=""
                                name="name"
                                placeholder="Enter product Name"
                                onChange={handleChange}
                                value={Product.name}
                             
                            />
                        </div>
                    </div>
                    <div className="form-group row">
                        <label for="leaderITNum" className="col-sm-3 col-form-label">
                        price
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id="price"
                                name="price"
                                placeholder="Enter price"
                                onChange={handleChange}
                                value={Product.price}
                                required
                            />
                        </div>
                    </div>
                    <div className="form-group row">
                        <label for="topicName" className="col-sm-3 col-form-label">
                            Product description 
                        </label>
                        <div className="col-sm-8">
                            <input
                                type="text"
                                className="form-control"
                                id="description"
                                name="description"
                                placeholder="Enter description"
                                onChange={handleChange}
                                value={Product.description}
                                required
                            />
                        </div>
                    </div>

                   

                    <div className="form-group row">
                        <div className="col-sm-10">
                            <button type="submit" className="btn btn-primary">
                                <b >Update</b>
                            </button>

                        </div>
                    </div>
                </form>






    </div>
  )
}

export default UpdateProduct

service

import axios from 'axios';

const LoginURL ='http://localhost:3000/user/login';
const RegisterURL = "http://localhost:3000/user/register";

export async function loginFunction(data){

    let alldata = {
        email: data.email,
        passowrd: data.passowrd
    }

return await axios.post(LoginURL , alldata);
}

export async function RegisterUsers(data){

    var alldata={
      
        name:data?.name,
        email:data?.email,
        passowrd:data?.passowrd,
        userRole:data?.userRole
    }

return await axios.post(RegisterURL , alldata)


}
**App.js**
import  {useEffect, useState } from 'react';
import AllProdcut from './components/AllProdcut';
import UpdateProduct from './components/UpdateProduct';
import CreateProduct from './components/CreateProduct';
import Login9 from './components/Login';
import RegisterUser from './components/RegisterUser';
import Navbar from './components/Navbar';

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Login9 from './components/Login';

 const  App=()=> {

  const [loggedUser, setloggedUser] = useState(null)
 
  useEffect(() => {
    setloggedUser(localStorage.getItem("token"));
}, [])


  return (

    <div >

<Router>
{loggedUser!== null ? <Navbar/> : <></>}
          <Routes>
            <Route  exact path="/" element={<Login9/>}/>
            <Route  path="/main" element={<AllProdcut/>} />
            <Route  path="/RegisterUser" element={<RegisterUser/>} />
            <Route  path="/Login9" element={<Login9/>} />
            <Route path="/products/:id" element={<UpdateProduct />} />
            <Route path="/CreateProduct" element={<CreateProduct />} />
            </Routes>
            </Router></div>

  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";


ReactDOM.render(
        <App />,
    document.getElementById("app")
);
  • Related