【发布时间】:2022-01-12 06:27:15
【问题描述】:
我尝试使用mongoose、express、bcrypt 和nodejs 为我当前尝试为用户设置登录页面的页面进行授权。不幸的是,当我尝试输入名称和密码时,我收到以下错误消息:
XHRPOSThttp://localhost:3000/api/register [HTTP/1.1 400 错误请求 48ms] Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我的 login.js 代码如下所示:
router.get('/', async (req, res) => {
//const articles = await Object.values(ArticlesWeb.articles).filter(all => all.publish ==='True');
//res.render('futureweb', {articles: articles});
res.render('login')
});
router.post('/api/register', async (req, res) => {
res.json({status: 'ok'})
if(!username || typeof username !== 'string'){
return res.json({status: 'error', error: 'Invalid username'})
}
if(!password || typeof username !== 'string'){
return res.json({status: 'error', error: 'Invalid password'})
}
if (password.length < 5){
return res.json({
status: 'error',
error: 'Password is too short. Password should at least have 6 characters.'
})
}
const password = await bcrypt.hash(password, 10)
try {
const response = await User.create({
username,
password})
} catch (error) {
if (error.code === 11000){
//duplicate key
return res.json({status: 'error', error: 'Username already in use'})
}
throw error
console.log(error)
}
}
)
login.ejs 文件的代码包括我从 POST 请求中获取 json 数据的部分:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="reg-form">
<input type="text" id="username" placeholder="Username"/>
<input type="password" id="password" placeholder="Password"/>
<input type="submit" value="Submit Form"/>
</form>
<script>
const form = document.getElementById('reg-form')
form.addEventListener('submit', registerUser)
// 1. Send data as JSON - favored in node.js
//2 send data as urlencoded - very popular in PHP
async function registerUser(event) {
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.parse(JSON.stringify({
username, password
}))
}).then((res) => res.json())
}
</script>
</body>
</html>
谁能提示我的代码有什么问题?
【问题讨论】:
标签: javascript node.js json mongoose