首页 > 解决方案 > 如何获取状态码为 400 的响应 api?

问题描述

我使用 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"
        }
    ]

标签: javascriptnode.jsexpressaxios

解决方案


你可以这样做

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;
    }

推荐阅读