我正面临一个错误,而作出的帖子登录请求。
我在Netlify 这里上部署了前端,在Heroku 这里上部署了后端。这是我的后端日志https://dashboard.heroku.com/apps/my-notebook-mohit/logs。
我得到了
`users.findOne()` buffering timed out after 10000ms
在heroku原木中却找不到原因。
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 (见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;
附件是错误屏幕截图。
用户模式
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;
来自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
发布于 2022-01-19 16:26:42
当数据库未连接时会发生这种类型的日志,因此请检查以下内容:
mongoose.connect(......)
代码加载吗?发布于 2022-05-05 18:29:12
我经历了这个错误,经过几次搜索,这是因为数据库的问题。
适用于使用MongoDB的用户
检查mongoDB左侧的网络访问部分。加上你的IP地址。对我来说,我只是在测试,所以我允许从任何地方访问。(我不建议)。
试试看。
https://stackoverflow.com/questions/70771062
复制相似问题