javascript - 无法将准确的错误消息从nodejs发送到浏览器

标签 javascript node.js vue.js

在我的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/

相关文章:

javascript - 为什么 header 中的内容类型仍然是文本/纯文本,尽管我将其设置为 application/json

javascript - 比较 2 个数组并检查位置

javascript - 当路径有空格时,NodeJS fs.writeFile 在 Linux 上失败

javascript - 尝试将 json 值与局部变量相乘时出现 NaN

javascript - Vuex:无法更改 Action 中深度嵌套的状态数据

node.js - NodeJs/Express Vue CLI3 应用程序错误无法设置未定义的属性渲染

javascript - vue组件外部的访问方法

javascript - Jquery滚动多个使li标签处于事件状态

javascript - 从简单的模块模式迁移到 RequireJS AMD

node.js - 在 Express.js 应用程序中存储来自 Google 日历 Node.js 示例的事件列表