[英]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.我在发出 POST 登录请求时遇到错误。
I had deployed the frontend on Netlify here and the backend on Heroku here .我在这里Netlify 上部署了前端,在这里Heroku 上部署了后端。 This is my backend logs https://dashboard.heroku.com/apps/my-notebook-mohit/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.在 heroku 日志中找不到原因。
LoginPage.js登录页面.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) auth.js (见路线2)
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来自 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:当您的数据库未连接时,会发生这种类型的日志,因此请检查以下事项:
mongoose.connect(......)
code loadingmongoose.connect(......)
代码加载I run through this error and after a few searching it is because of an issue with the database.我遇到了这个错误,经过几次搜索,这是因为数据库有问题。
For those using MongoDB对于那些使用 MongoDB 的人
Check the.network access section on the left side of mongoDB. Add your IP address.检查mongoDB左侧的.network访问部分。添加您的IP地址。 For me I'm just testing things out so I allowed access from everywhere.
对我来说,我只是在测试,所以我允许从任何地方访问。 (I don't suggest it).
(我不建议这样做)。
Give it a try.试一试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.