简体   繁体   中英

Not able to get response , showing Operation `users.findOne()` buffering timed out after 10000ms`

I am facing an error while making the POST login request.

I had deployed the frontend on Netlify here and the backend on Heroku here . This is my backend logs https://dashboard.heroku.com/apps/my-notebook-mohit/logs .

I am getting

`users.findOne()` buffering timed out after 10000ms

in the heroku logs but unable to find the reason.

LoginPage.js

import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import imgpath from "../assets/notepic.jpg";
import { motion } from "framer-motion";

const Login = (props) => {
  let history = useHistory();
  let port = process.env.PORT;
  ....
 
  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch(`https://my-notebook-mohit.herokuapp.com:/api/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: credentials.email,
        password: credentials.password,
      }),
    });
    const json = await response.json();
    if (json.success === true) {
      //storing the authtoken
      localStorage.setItem("token", json.authToken);
      props.showAlert("User logged in successfully", "info");
      history.push("/");
    } else {
      props.showAlert("invalid Credentials", "danger");
    }
    console.log(json);
  };

  return (
   .....
   <form onSubmit={handleSubmit} className="login-form">
           .....
           ....
   </form>
  ...
  ...

};

export default Login;

auth.js (see route2)

const express = require("express");
const { body, validationResult } = require("express-validator");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "mohitisagood$boy";
const fecthUser = require("../middleware/fetchUser");

//ROUTE 1 :Creating a User :POST - "/api/auth/createuser"
router.post(
  "/createuser",
  [
    body("name", "Name must have at least 3 characters").isLength({ min: 3 }),
    body("email", "Enter a valid email").isEmail(),
  ],
  async (req, res) => {

    let success = false;
    //If there are errors, then return bad request + Errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({success, errors: errors.array() });
    }

    try {
      //Check whether email exists
      let user = await User.findOne({ email: req.body.email });
      //console.log("user.nemail = " + user);
      if (user) {
        //console.log(user.email);
        return res.status(400).json({success, error: "Email Already Taken" });
      }

      //hashing the password here
      const salt = await bcrypt.genSalt(10);
      const secPass = await bcrypt.hash(req.body.password, salt);
      //user is created
      user = await User.create({
        name: req.body.name,
        email: req.body.email,
        password: secPass,
      });

      //passing the id as data to make jwt token
      const data = {
        user: {
          id: user.id,
        },
      };

      const authToken = jwt.sign(data, JWT_SECRET);
      //console.log(authToken)

      
      success = true;
      //res.json(user);
      res.json({success, authToken });
    } catch (error) {
      console.log(error.message);
      res.status(500).send("internal server error");
    }
  }
);

//ROUTE 2 :Authenticating a User :POST - "/api/auth/login"
router.post(
  "/login",

  body("email", "Enter a valid email").isEmail(),

  async (req, res) => {
    //If there are errors, then return bad request + Errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password } = req.body;
    
    let success = false;

    try {
      let user = await User.findOne({ email });

      // console.log("user - "+user)

      if (!user) {
        res.status(400).json({success,error:"Login with correct credentials!"});
      }

      //compare the pwd bw 'hash of pwd entered' & 'hash from your pwdDB'
      const passwordCompare = await bcrypt.compare(password, user.password);

      if (!passwordCompare) {
        res.status(400).json({success,error:"Login with correct credentials!"});
      }
      //nodemon crashes whenever PASSWORD === NULL


      const payload = {
        user: {
          id: user.id,
        },
      };

      const authToken = jwt.sign(payload, JWT_SECRET);
      
      success = true;
      res.json({ success, authToken });
    } catch (error) {
      console.log(error.message);
      res.status(500).send("Internal Server Error");
    }
  }
);

//ROUTE 3 :Get Loggedin user details  :GET - "/api/auth/getUser" LOGIN REQUIRED;

router.get("/getUser", fecthUser, async (req, res) => {
  try {
    const userid = req.user.id; //gets userid from fetchUser middleware fn
    let user = await User.findById(userid);
    res.send(user);
  } catch (error) {
    console.log(error.message);
    res.status(500).send("Internal Server Error");
  }
});

module.exports = router;


Attached is the error screenshot

错误

User Schema

const mongoose = require("mongoose");
const { Schema } = mongoose;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    validate(value) {
      if(value.length < 5) {
        throw new Error( "Minimum length is 5 characters");
      }
      else if (!value.match(/\d/) || !value.match(/[a-zA-Z]/) ) {
        throw new Error(
          "Password must contain at least one letter and one number"
        );
      }

    }
    
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

const User = mongoose.model("users", UserSchema);
module.exports = User;

logs from heroku

2022-01-19T13:53:34.121500+00:00 heroku[web.1]: Starting process with command `npm start`
2022-01-19T13:53:35.255548+00:00 app[web.1]: 
2022-01-19T13:53:35.255561+00:00 app[web.1]: > my-notebook-backend@1.0.0 start
2022-01-19T13:53:35.255561+00:00 app[web.1]: > node index.js
2022-01-19T13:53:35.255562+00:00 app[web.1]: 
2022-01-19T13:53:35.891508+00:00 heroku[web.1]: State changed from starting to up
2022-01-19T13:53:36.331033+00:00 heroku[router]: at=info method=GET path="/" host=my-notebook-mohit.herokuapp.com request_id=1f84a49c-8785-4483-a148-1ee8e2d02733 fwd="116.179.32.83" dyno=web.1 connect=0ms service=6ms status=404 bytes=415 protocol=http
2022-01-19T13:53:35.670089+00:00 app[web.1]: my-notebook backend listening at http://localhost:28800
2022-01-19T13:54:05.041186+00:00 heroku[router]: at=info method=OPTIONS path="/api/auth/login" host=my-notebook-mohit.herokuapp.com request_id=ce943a7c-d99d-41a9-965f-7d9f420c0abc fwd="157.34.168.68" dyno=web.1 connect=0ms service=3ms status=204 bytes=301 protocol=https
2022-01-19T13:54:05.563326+00:00 app[web.1]: Connected to Mongo Successfully!
2022-01-19T13:54:15.670120+00:00 heroku[router]: at=info method=POST path="/api/auth/login" host=my-notebook-mohit.herokuapp.com request_id=9527d47f-e054-4f83-bb95-7e99582dab31 fwd="157.34.168.68" dyno=web.1 connect=0ms service=10030ms status=500 bytes=272 protocol=https
2022-01-19T13:54:15.666381+00:00 app[web.1]: Operation `users.findOne()` buffering timed out after 10000ms
2022-01-19T13:54:17.866396+00:00 app[web.1]: Operation `users.findOne()` buffering timed out after 10000ms
2022-01-19T13:54:17.868120+00:00 heroku[router]: at=info method=POST path="/api/auth/login" host=my-notebook-mohit.herokuapp.com request_id=4e9561f7-1050-4afb-9f6b-bf04c876b858 fwd="157.34.168.68" dyno=web.1 connect=0ms service=10007ms status=500 bytes=272 protocol=https

This type of log happens when your database is not connected, so check the following things:

  • Is your url correct in your connection string.
  • Is your mongoose.connect(......) code loading
  • Also maybe your MongoDB process became a zombie process and you have to restart it.

I run through this error and after a few searching it is because of an issue with the database.

For those using MongoDB

Check the.network access section on the left side of mongoDB. Add your IP address. For me I'm just testing things out so I allowed access from everywhere. (I don't suggest it).

Give it a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM