繁体   English   中英

如何获得状态码为 400 的响应 api?

[英]how to get the response api with status code is 400?

I consume api and when the api returns 200 status code, I return the response, but when the api returns 400 status code the api returns array with the errors, my questions is how can i get this array errors and return this array.

编码

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"
        }
    ]

你可以这样做

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

只需要调用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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM