在我的nodejs应用程序中,我设置了一些错误处理,但确切的错误消息不会像我设置的那样发送到浏览器。相反,会发送一个不包含特定错误消息的错误对象。但是,错误消息可以在nodejs控制台中打印出来,但不能发送到浏览器。前端是vuejs。
这是我的nodejs代码。
//To sign up a new user
userRoutes.post('/users', async (req, res) => {
try {
//Check if the user is already registered
const registeredUser = await User.findOne({ email: req.body.email })
if (registeredUser) {
console.log("There is a user already") //Prints out in the node console
throw new Error("This email is already registered") //Does not sent this message to the broswer
}
const user = new User(req.body)
await user.save()
sendWelcomeEmail(user.email, user.firstName)
const token = await user.generateAuthToken()
res.status(201).send({ user, token })
} catch (e) {
console.log(e) //Prints out the error message in the node console
res.status(400).send(e) //Sends a complex error object without the error message
}
})
下面是发送到浏览器的复杂错误对象:
{ "error": { "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=utf-8" }, "baseURL": "http://localhost:3000", "method": "post", "url": "http://localhost:3000/users", "data": "{\"firstName\":\"Efosa\",\"lastName\":\"Humna\",\"email\":\"user@yahoo.com\",\"password\":\"uyewhwehwj\"}" }, "request": {}, "response": { "data": {}, "status": 500, "statusText": "Internal Server Error", "headers": { "content-type": "application/json; charset=utf-8" }, "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=utf-8" }, "baseURL": "http://localhost:3000", "method": "post", "url": "http://localhost:3000/users", "data": "{\"firstName\":\"Efosa\",\"lastName\":\"Humna\",\"email\":\"user@yahoo.com\",\"password\":\"uyewhwehwj\"}" }, "request": {} } } }
请有人帮我指出我做错了什么?
最佳答案
我假设您正在使用 axios for xhr 和 vue,那么您应该使用 json 响应:
res.status(400).json(e.message) //send error message
创建一个全局中间件来处理 Express 应用程序中的所有错误是一个好习惯,因此在 try/catch 中,您可以使用 next(err)
将错误发送到中间件,然后在错误中间件中处理它,其中可以根据环境格式化错误(例如,在开发中,发送错误的完整堆栈跟踪,在生产中仅发送常见消息)。 next
是路由器回调函数的第三个参数。
关于javascript - 无法将准确的错误消息从nodejs发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923741/