Question
In the daily process of docking with the back-end interface, it is often encountered that the interface field has a null value, such as
{
code:0,
msg:'success',
result:null
}
At this time, when we get result.userInfo again, JavaScript will report an error. Therefore, the front-end not only checks whether the interface status code is 0, but also checks whether the result is the expected object type.
That is from the original
if (res.data.code === 0)
To
if (res.data.code === 0&&res.data.result)
Especially when we expect the data structure to be
{
code:0,
result:{
userInfo:{
userName:''
}
}
}
In order to obtain the value of userName smoothly, we need to make three judgments
let userName = ''
if (res.data.result&&res.data.result.userInfo&&res.data.result.userInfo.userName)
userName = res.data.result.userInfo.userName
Very headache
And 98% of the backends are not willing to return according to the predetermined data structure
That is to cause object/string/number/array to be null
In time you finally defeated the backend and agreed to return in accordance with the format,
But after all, the interface returns untrusted
So I envisioned a solution mainly to solve so many if judgments and format the interface return as we want.
By retaining the basic format, and then returning the interface to merge into the basic data
The advantage of this is
- The expected data structure is completely retained
- When debugging the code, you can clearly and intuitively see the data format returned by the current interface to enhance readability
- Convenient to do interface mock expansion
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。