【问题标题】:Setting up authorization: unexpected character at line 1 column 1 of the JSON data设置授权:JSON 数据的第 1 行第 1 列出现意外字符
【发布时间】:2022-01-12 06:27:15
【问题描述】:

我尝试使用mongooseexpressbcryptnodejs 为我当前尝试为用户设置登录页面的页面进行授权。不幸的是,当我尝试输入名称和密码时,我收到以下错误消息:

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


    【解决方案1】:

    你快到了。试试这个,确保不要同时使用 parse 和 stringify。

     const result = await fetch('/api/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username, password
                })
            }).then((res) => res.json())
            .then(data => console.log("data is here -> ", data))
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2014-11-02
      • 1970-01-01
      • 2023-02-08
      • 2019-01-19
      • 1970-01-01
      • 2023-03-11
      • 2020-09-03
      • 2016-05-25
      相关资源
      最近更新 更多