我正在使用MongoDB,NodeJS,ejs,护照等...
当我尝试使用数据库中已经存在的用户名创建新用户时,我从服务器端收到错误
{UserExistsError:具有给定用户名的用户已经 注册 在Promise.resolve.then.then.then处(my / path / for / node_modules / passport-local-mongoose / index.js:238:17) 在process._tickCallback(internal / process / next_tick.js:68:7)处名称:“ UserExistsError”,消息:“具有给定用户名的用户是 已经注册'}
并且不在客户端添加任何消息,仅刷新页面并保留在主页上,但不知道这样做的好方法,我希望客户端知道用户名已被使用。.
谢谢!
我的服务器端:
const express = require('express'),
passport = require('passport'),
User = require('../models/users.js'),
app = express.Router();
//Get User Data
exports.get_user_data = function(req, res) {
let userid = req.user._id;
User.findById(userid)
.exec((err, user) => {
if (err) {
console.log(err);
} else {
res.send(user);
}
});
}
//Render Register
exports.render_new_register = function(req, res) {
}
//Create New User Account
exports.create_new_account = function(req, res) {
User.register(new User({
username: req.body.username,
companyname: req.body.companyname,
companyimageURL: req.body.companyimageURL
}),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
return res.redirect('/')
}
console.log("SUCCESS");
logUser(user, req, res);
}
)
};
//Render Login
exports.render_login_account = function(req, res) {
};
//Render Logout - end of user session
exports.render_logout_account_endSession = function(req, res) {
req.logout();
res.redirect('/');
};
//Authenticate User Login
exports.user_login_authenticate =
passport.authenticate("local")
function logUser(user, req, res) {
req.login(user, (err) => {
if (err) {
console.log(err);
return res.redirect('/');
}
res.redirect('/dashboard') //register with success
})
}
我的客户端
<!-- Modal REGIST SIGNUP-->
<div class="modal fade" id="myModalRegist" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="outline: none; border: none">
<span style="outline: none; border: none" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="modal__header" class="container text-center">
<h1 class="modal__title">WELCOME</h1>
<p class="modal__paragraph"> Create a new account</p>
<form action="/getstarted" method="POST">
<div class="form-group">
<input type="text" class="form-control" aria-describedby="username" placeholder="enter username" name="username" required>
</div>
<div class="form-group">
<input id="passwordregist" type="password" class="form-control" placeholder="min 6 characters" required minlength="6" name="password">
</div>
<div class="form-group">
<input id="passwordregist_confirm" type="password" class="form-control" placeholder="min 6 characters" required minlength="6" name="password_confirm">
</div>
<div class="form-group">
<input type="companyname" class="form-control" placeholder="company name" name="companyname" required>
</div>
<div class="form-group">
<input type="companyimageURL" class="form-control" placeholder="company image URL" name="companyimageURL" required>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" required>
<label class="form-check-label" for="check">Check me out</label>
<div id="alertconfirm"></div>
</div>
<button id="registersubmitbutton" type="submit" class="btn btn-default button_modal button_modal--colors">Get Started</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- / Modal REGIST SIGNUP-->
<script>
$('#registersubmitbutton').on('click', function(e) {
let password = $("#passwordregist").val();
let password_confirm = $("#passwordregist_confirm").val();
if (password !== password_confirm) {
if ($('#alertconfirm').children().length === 0) {
$('#alertconfirm').append(
`<div class="alert" role="alert" style="font-size: 11px; color: #ec1818; padding: 0">
Oops! Passwords don't match. Please try again.</div>`
)
}
return false;
}
});
</script>
答案 0 :(得分:1)
如果您想显示一条消息,则可能必须在click方法中使用异步调用( 我更喜欢创建onSubmit方法 ),您可以使用AJAX。
这是一个如何使用POST创建AJAX的示例: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send#Example_POST。
请记住,响应是对象 xhr.responseText 。
xhr.onreadystatechange = function() {
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
console.log(xhr.responseText);
}
}
另一方面,您必须更改logUser方法以返回有效的JSON:
function logUser(user, req, res) {
req.login(user, (err) => {
if (err) {
return res.json({ error: error });
}
res.json({ error: null, message: "User registered" });
})
}
答案 1 :(得分:1)
您可以通过先检查用户存在或不通过用户名
来实现示例:
userCtr.create_new_account = (req, res) => {
const {
username, companyname, companyimageURL
} = req.body;
const query = {
username: username
}
User.findOne(query)
.then((user) => {
if (!user) {
//create User.
} else {
res.status(400).json({ error: 'user already exists' });
}
})
.catch((err) => {
//return error
});
};