【问题标题】:How to get the data associated with the error response back?如何取回与错误响应相关的数据?
【发布时间】:2019-05-30 18:46:03
【问题描述】:

我正在从前端向我的后端中的路由发出请求,该路由正在验证与用户关联的令牌,如果令牌已过期,它将向前端发送错误响应。我正在发送一些json,但是在对catch 块中的错误消息执行console.log 时,未显示随错误响应发送的json。

像这样发送错误响应

res.status(401).json({
                message: 'User session has expired'
            })

但是我在前端的 catch 块中得到的响应没有带有错误发送的 json 的迹象。

POST http://localhost:3001/check-validation 401(未经授权) 错误:请求失败,状态码为 401 在 createError (createError.js:17) 定居时 (settle.js:19) 在 XMLHttpRequest.handleLoad (xhr.js:78)

我不明白为什么没有显示错误响应发送的json以及如何获取它?

【问题讨论】:

    标签: express error-handling


    【解决方案1】:

    在对错误执行 console.log 时,仅显示错误的堆栈跟踪,而不显示与其关联的数据。可以获取与它一起发送的数据,这取决于请求的提出方式或提出请求的库。如果请求是由axios 提出的,则可以执行以下操作:

    axios.post('/formulas/create', {
        name: "",
        parts: ""
    })
    .then(response => { 
        console.log(response)
    })
    .catch(error => {
        console.log(error.response.data.message)
    });
    

    在这里,在 axios 中,错误的详细信息将包含在 error.response 中。然而,如果请求是由 fetch API 发出的,那么以下内容可以解决问题:

    fetch('/401').then(function(response) {
      if (response.status === 401) {
        return response.json()
      }
    }).then(function(object) {
      console.log(object.message)
    })
    

    P.S 我对这个问题进行了很多搜索,但没有得到关于 SO 的答案,也没有得到任何关于它的文章或文档,即使是关于错误处理的官方 Express 文档也没有帮助。最后,我了解到问题出在用于发出请求的库上。这就是为什么回答我自己的问题以在 SO 上标记这个问题的存在。详细讨论可以在这里找到related to axios 和这里related to fetch api

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2018-04-29
      • 2021-11-07
      • 2022-09-22
      • 1970-01-01
      相关资源
      最近更新 更多