这是我的全部代码。我尝试了很多仍然无法解决的问题。邮递员上的发布请求显示负载,然后崩溃。没有错误消息
const express = require('express');
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
// // Connection URL
var MongoClient = require('mongodb').MongoClient;
var db = "mongodb://localhost:27017/userDb";
MongoClient.connect(db, { useNewUrlParser: true }, function (err, db) {
if (err) throw err;
console.log("Mongo DB Connected...!");
// db.close();
});
//用户数据库
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
hash: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
});
var User = mongoose.model('User', UserSchema);
//注册新用户
app.post('/register', async (req, res) => {
console.log('try registering : ', req.body);
console.log(User);
//检查该用户是否已经存在
console.log('in here');
//这是它不起作用的地方
let user = await User.findOne({ username: req.body.username });
if (user) {
return res.status(400).send('That user already exisits!');
}
// Encrypt Password
try {
console.log('Encrypt');
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(req.body.password, salt, (err, hash) => {
console.log('-----password:', hash, '& salt', salt, '-----');
passwordHash = hash;
saltHash = salt;
user = new User({
username: req.body.username,
password: passwordHash,
hash: saltHash,
});
console.log(user);
user.save();
res.send('Registered');
});
});
} catch (err) {
console.log(err);
}
});
登录用户
app.post('/login', async (req, res) => {
console.log('try Login : ', req.body);
let user = await User.findOne({ username: req.body.username });
// console.log(user);
if (!user) {
return res.status(400).send('Incorrect username');
}
console.log(user);
console.log('decrypting entered password');
解密密码
const passwordHash = await bcrypt.hash(req.body.password, user.hash);
if (passwordHash == user.password) {
// console.log("in")
res.send('You are logged in!');
} else {
console.log('incorrect password');
}
});
我在这里创建我的端口
//PORT
const port = process.env.PORT || 3020;
app.listen(port, () => console.log(`listening on port ${port}...`));
答案 0 :(得分:0)
您需要将User.findOne更改为以下代码:
let user = await User.findOne({ username: req.body.username }).exec();
更改此设置,让我们知道结果。
答案 1 :(得分:0)
在这里,我已修复您的代码。 看这里。 link
我想指出一点。
仅此而已。尝试学习更好的代码结构。如有疑问,请告诉我。