【发布时间】:2021-11-25 09:36:50
【问题描述】:
我正在通过对我的 API 的异步调用为我的应用程序构建登录功能。我的问题是,即使 express 抛出错误, .then() 仍然在运行时出现错误,而不是实际的用户和令牌响应。我不确定为什么登录功能没有“捕捉”错误,而是在 .then() 中运行代码。
我的快递功能:
// express funciton to login a user
app.post('/api/users/login', (req, res) => {
const { email, password } = req.body
database.getUser(email, password, (error, user) => {
console.log(error)
if (error) {
res.send({ error })
//errors are being handled here and are returned in the result of my
frontend API call
return
}
const token = jwt.generateToken({ userId: user.id, name: user.name, email: user.email })
res.send({ token: token, user:user })
})
})
//getUser function with mySQL query
function getUser(email, password, callback) {
const query = `
SELECT id, name, email, password
FROM users
WHERE email = ?
`
const params = [email]
connection.query(query, params, (error, results, fields) => {
if (!results || results.length === 0) {
callback(Error("Email is incorrect"))
return
}
const user = results[0]
bcrypt.compare(password, user.password, (error, same) => {
console.log(error)
if (error) {
callback(error)
return
}
if (!same) {
callback(Error("Password is incorrect"))
return
}
callback(null, user)
})
})
}
exports.getUser = getUser
我在 Next.js 中的登录功能:
const login = async ({ email, password }) => {
return await axios.post('http://localhost:4200/api/users/login', {
email: email,
password: password
})
.then((result) => {
//when backend throws error, they are contained here as "result.error" still running these lines of code
sessionStorage.setItem('token', result.data.token);
axios.defaults.headers.common['Authorization'] = "Bearer " + result.data.token;
console.log('user signed in');
})
.catch((err) => {
//want errors to be directed here instead so I can properly handle them within the UI
console.error("Username or password is incorrect!!")
})
};
【问题讨论】:
-
尝试设置错误状态码。
res.status(401).json({ error }) -
如果有帮助请告诉我
标签: javascript node.js reactjs express next.js