VM39:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

时间:2021-03-25 18:17:04

标签: javascript node.js json mongodb express

我正在使用 Node.js express.js 和 mongoDB 创建一个简单的登录系统来保存用户。 创建账号后,去登录,输入数据,登录报错

VM39:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Server.js 文件

 app.post('/api/login', async (req, res) => {
const { email, password } = req.body
const user = await User.findOne({ email }).lean()

if (!user) {
    return res.json({ status: 'error', error: 'Invalid email or password' })
}

if (await bcrypt.compare(password, user.password)) {
    
    const token = jwt.sign(
        {
            id: user._id,
            email: user.email
        },
        JWT_SECRET
    )

    return res.redirect('/dashboard');
}

res.json({ status: 'error', error: 'Invalid username or password' })

})

app.js 文件

async function login(event) {
event.preventDefault()
const email = loginEmail.value;
const password = loginPassword.value;

const result = await fetch('/api/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        email,
        password
    })
}).then((res) => res.json())

if (result.status === 'ok') {
    // everythign went fine
    console.log('Got the token: ', result.data)
    localStorage.setItem('token', result.data)
    alert('Success')
} else {
    alert(result.error)
}

}

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

试试这个提取:

@ExceptionHandler