javascript - 如何获取状态码为 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"
}
]
解决方案
你可以这样做
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;
}
推荐阅读
- excel - 删除/合并 VBA 中的重复 ID
- python - auto-py-to-exe : 未找到模块请求
- php - 在回声中使用三元运算符?
- android - java.lang.NullPointerException - .onCreate - 尝试在空对象引用上调用虚拟方法
- node.js - 如何从通过 HTTP 可调用函数发送的请求中获取数据?
- laravel - 无法在 jenseger mongodb 中使用 $lookup 来合并集合
- javascript - 有条件地更改对象属性
- sql - Big Query 中的 SQLSTATE 和 SQLCODE 等效项
- ios - 在没有可可的情况下集成 Firebase 没有这样的模块“Firebase”?
- javascript - 单击时从数组中删除对象