【问题标题】:Unable to send exact error messages from nodejs to browser无法从 nodejs 向浏览器发送确切的错误消息
【发布时间】:2019-07-07 15:51:43
【问题描述】:

在我的 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": {} } } }

请有人帮我指出我做错了什么?

【问题讨论】:

  • 您确定您实际上是在执行 catch 块中的代码吗?您引用的对象的 error.response 部分说:"status": 500, "statusText": "Internal Server Error", 这是状态 500,而不是您尝试抛出的 400
  • 这不是从服务器发送的复杂对象。当服务器响应为4xx 或5xx 时,这就是axios 响应的样子。也就是说——无论如何,你不会发回 JSON 对象。您正在发送一个纯 HTML 文档。
  • 试试这个res.status(400).json({ error: e.message });

标签: javascript node.js vue.js


【解决方案1】:

我假设你使用 axios for xhr 和 vue,那么你应该使用 json 响应:

res.status(400).json(e.message) //send error message

创建一个全局中间件来处理 express 应用程序中的所有错误是一个好习惯,因此在 try/catch 中,您将错误发送到带有 next(err) 的中间件,然后在可以格式化错误的错误中间件中处理它取决于环境(例如在开发中,发送错误的完整堆栈跟踪,在生产中仅发送常见消息)。 next 是路由器回调函数的第三个参数。

【讨论】:

  • 谢谢理查德。但是, res.status(400).json(e.message) 给出了同样的问题,并且使用 next(err) 仅在该行之后继续执行代码,而不是将错误发送到我创建的中间件。我将错误中间件作为 userRoute 中异步函数之后的下一个参数。还是我错了?
  • 您应该创建全局中间件并将其作为最后一个中间件放置在您的应用 js 中,还要记住错误中间件必须有 4 个参数(err、req、res、next)。你能提供一些关于 git 的示例代码并重现错误吗?
  • 谢谢理查德。 res.status(400).send(e.message) 已经为我解决了。我还必须使用 error.response.data 在前端提取错误消息。
猜你喜欢
  • 2015-04-07
  • 2013-04-02
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 2021-03-01
  • 2021-05-29
相关资源
最近更新 更多