【问题标题】:how to get the response api with status code is 400?如何获取状态码为 400 的响应 api?
【发布时间】:2021-04-17 05:23:14
【问题描述】:

我使用 api,当 api 返回 200 状态码时,我返回响应,但是当 api 返回 400 状态码时,api 返回带有错误的数组,我的问题是如何获取此数组错误并返回此数组.

代码

try {
        const config = {
            method: 'get',
            url: 'http://localhost:4000/api/orders',
            headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
        }
        const result = await axios(config)
        return result.data
    } catch (error) {
        console.log('error ' + error)
        returns result.data.errors
    }

这个状态码的响应是 400。

"errors": [
        {
            "value": "96db259b-2239-4abb-9b9d-a682ssa1de6b3c",
            "msg": "the API key 96db259b-2239-4abb-9b9d-a682ssa1de6b3c is invalid",
            "param": "key",
            "location": "headers"
        }
    ]

【问题讨论】:

    标签: javascript node.js express axios


    【解决方案1】:

    你可以这样做

    try {
            const config = {
                method: 'get',
                url: 'http://localhost:4000/api/orders',
                headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
            }
            const result = await axios(config)
            if(result.status != 200) {
             throw new Error(`[Status ${result.status}] Something went wrong `);
            }
            return result.data
        } catch (error) {
            console.log('error ' + error)
            returns error.message;
        }
    

    【讨论】:

      【解决方案2】:

      只需要调用error的message属性,例如:

      try {
              const config = {
                  method: 'get',
                  url: 'http://localhost:4000/api/orders',
                  headers: {'Key': '96db259b-2239-4abb-9b9d-a682a1de6b3c'}
              }
              const result = await axios(config)
              return result.data // this only called with success response, status code 200
          } catch (error) {
              console.log('error ' + error)
              returns error.message;
          }
      

      【讨论】:

        猜你喜欢
        • 2021-10-11
        • 2021-02-13
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2021-11-07
        • 1970-01-01
        • 2011-07-17
        相关资源
        最近更新 更多