Getting EMPTY OUTPUT When Testing ON THUNDER CLIENT

116 Views Asked by At

I am following a youtube playlist regarding MERN STACK project and I am stuck at some instance please help

below is the code

index.js

 
const express = require('express')
const app = express()
const port = 5000

const mongoDB = require("./db")
mongoDB();

app.use((req, res, next)=>{
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
})

app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.use(express.json());
app.use('/api', require("./Routes/CreateUser"));
app.use('/api', require("./Routes/DisplayData"));

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

db.js

const mongoose = require("mongoose");

const mongoURI =
  "mongodb://<userName>:<password>@ac-czejupk-shard-00-00.e8wdets.mongodb.net:27017,ac-czejupk-shard-00-01.e8wdets.mongodb.net:27017,ac-czejupk-shard-00-02.e8wdets.mongodb.net:27017/?ssl=true&replicaSet=atlas-11o3y9-shard-0&authSource=admin&retryWrites=true&w=majority";
const mongoDB = async () => {
  await mongoose.connect(
    mongoURI,
    { useNewUrlParser: true },
    async (err, result) => {
      if (err) console.log("---", err);
      else {
        console.log("connected");
        const fetched_data = await mongoose.connection.db.collection(
          "food_items"
        );

        fetched_data.find({}).toArray(async function (err, data) {
          const foodCat = await mongoose.connection.db.collection(
            "food_category"
          );

          foodCat.find({}).toArray(function (err, catData) {
            if (err) console.log(err);
            else {
              global.food_items = data;
              global.food_category = catData;
            }
          });
        });
      }
    }
  );
};

module.exports = mongoDB;

DisplayData.js


const express = require("express");
const router = express.Router();
const User = require("../models/User");
const { body, validationResult } = require("express-validator");



const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const jwtSecret = "myNameISApurvaMuthaye710";
router.post(
  "/createuser",
  [
    body("email").isEmail(),
    body("name").isLength({ min: 5 }),
    body("password").isLength({ min: 5 }),
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    const salt = await bcrypt.genSalt(10);
    let secPassword = await bcrypt.hash(req.body.password, salt);
    try {
      await User.create({
        name: req.body.name,
        password: secPassword,
        email: req.body.email,  
        location: req.body.location,
      });
      res.json({ success: true });
    } catch (error) {
      console.log(error);
      res.json({ success: false });
    }
  }
);

router.post(
  "/loginuser",
  [body("email").isEmail(), body("password").isLength({ min: 5 })],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    let email = req.body.email;
    try {
      let userData = await User.findOne({ email });
      if (!userData) {
        return res
          .status(400)
          .json({ errors: "Log in with correct credentials" });
      }
      const pwdCompare = await bcrypt.compare(req.body.password, userData.password)
      if (!pwdCompare) {
        return res
          .status(400)
          .json({ errors: "Log in with correct credentials" });
      }
      const data = {
        user: {
          id:userData.id
        }
      }
      const authToken = jwt.sign(data, jwtSecret);

      return res.json({ success: true , authToken:authToken});
    } catch (error) {
      console.log(error);
      res.json({ success: false });
    }
  }
);

module.exports = router;

package.json

{ "name": "backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "bcryptjs": "^2.4.3", "express": "^4.18.2", "express-validator": "^7.0.1", "jsonwebtoken": "^9.0.2", "mongodb": "^2.2.12", "mongodb-legacy": "^6.0.0", "mongoose": "^6.6.1", "nodemon": "^3.0.1", "react-jwt": "^1.2.0" } }

mongodb thunderclient

So after running the code and checking with thunder client the output should have been the list of data from "food_items" but I am getting empty output in the thunder client please help

0

There are 0 best solutions below