问题描述
我可以在我的网站上正常注册用户,但是当我用Postman测试它时,出现此错误:
MissingPasswordError: No password given
我也无法登录,因为密码/用户名组合不正确,所以肯定有问题,但是我一生都无法找出原因。
这是我的html输入框,用于输入密码:
<input type="password" class="input--text" name="password" id="password">
const btnSignup = document.querySelector('.btn').addEventListener('click',function () {
let username = document.querySelector('#username').value;
let password = document.querySelector('#password').value;
let bday = document.querySelector('#bday').value;
fetch('http://localhost:3000/users/signup',{
method: "post",headers: {
'Content-Type': 'application/json'
},body: JSON.stringify({
'username': username,'password': password,'bday': bday
})
}).then(response => {
return response.json();
}).then(json => {
if (json.status === 'success') {
let Feedback = document.querySelector('.alert');
Feedback.textContent = "Sign up successful!";
Feedback.classList.remove('hidden');
}
})
})
这是我在auth.js
控制器中的注册功能:
const signup = async (req,res,next) => {
const username = req.body.username;
const password = req.body.password;
const bday = req.body.bday;
const user = new Users({
username: username
});
/*user.bday = bday;*/
await user.setPassword(password);
await user.save()
.then(result => {
console.log(result.id);
let token = jwt.sign({
id: result._id
},"{this is a secret}");
res.json({
'status': 'success','data': {
'token': token
}
})
}).catch(error => {
res.json({
'status': 'error'
})
});
}
我添加了bodyParser,确保输入字段的名称正确,...
解决方法
解决了!原来我的代码是正确的,但是我忘记将Postman中的原始内容设置为JSON(默认为文本)。