【问题标题】:how to hanlde response status with axios async await如何使用 axios async await 处理响应状态
【发布时间】:2020-09-10 19:22:18
【问题描述】:

我有下面的sn-p

const url = 'https://someurl.com';
const options = {
            method: 'POST',
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: {
                property_one: value_one,
                property_two: value_two
            }
        };
const response = await axios(options);
const responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
    const data = await response.data;
    // do something with data
}

我们是否需要同时检查 response.statusresponse.statusText?此外,如果 response.data 具有来自后端的附加状态,例如:

{
      "transactionId": "123456789",
      "document": {
        "documentId": "123456",
        "status": "S"
      }
}

我们是否需要检查状态是否为“S”。如果是,我们如何检查 response.statusresponse.statusText

谢谢。

【问题讨论】:

    标签: async-await axios


    【解决方案1】:

    您应该在trycatch 语句中处理请求和响应

    请求:

    try {
        const res = await axios.post('url', body);
        //continue with res.data
    
    } catch (err) {
        const error = err.response.data;
        //throw alert or something
    }
    

    回复:

    try {
        //query
        res.status(200).json(data);
    
    } catch (err) {
        //error
        res.status(500).json('Server Error');
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2018-09-14
      • 2020-08-02
      • 2020-11-19
      • 2018-12-26
      • 2020-05-15
      • 2018-03-31
      • 2018-09-03
      • 2017-10-26
      相关资源
      最近更新 更多