簡體   English   中英

使用 Body.json() 承諾處理非 JSON 響應

[英]Handling non JSON response with a Body.json() promise

我正在嘗試創建一個方案來攔截和處理來自 API 中間件的請求,但是,無論出於何種原因,我都無法正確處理來自 API 端點的非 JSON 響應。 以下代碼段適用於 JSON 格式的服務器響應,但是如果用戶具有無效令牌,服務器返回一個簡單的未經授權的訪問響應,即使我向 json() 承諾提供錯誤回調,我也無法處理該響應. 未授權訪問響應消息在以下方案中丟失。

    const callAPI = () => { fetch('http://127.0.0.1:5000/auth/', {
        method: 'GET',
        headers: {
            'credentials': 'include',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Basic bXlKaGJHY2lPaUpJVXpJMU5pSXNJbVY0Y0NJNk1UUTVPRE15TVRNeU5pd2lhV0YwSWpveE5EazRNak0wT1RJMmZRLmV5SnBaQ0k2TVgwLllFdWdKNF9YM0NlWlcyR2l0SGtOZGdTNkpsRDhyRE9vZ2lkNGVvaVhiMEU6'
        }
    });
    };

    return callAPI().then(res => {
        return res.json().then(responseJSON => {
            if(responseJSON.status === 200){
                return dispatch({
                    type: type[1],
                    data: responseJSON,
                    message: success
                });
            } else if(responseJSON.status === 401) {
                return dispatch({
                    type: type[2],
                    message: responseJSON.message
                });
            }
            return Promise.resolve(json);
        }, (err) => {
            console.log(err.toString(), ' an error occured');
        });
    }, err => {
        console.log('An error occured. Please try again.');
    });

嘗試使用 Body 的 text 方法: res.text()

嘗試將您的響應處理代碼包裝在try...catch塊中,如下所示:

return callAPI().then(res => {
    try {
        return res.json().then(responseJSON => {
            [...]
    catch(e) {
        console.error(e);
    }
});

Body.json()在正文實際上不是 JSON 時拋出。 因此,您應該調用json()之前檢查正文是否包含 JSON。 請參閱https://developer.mozilla.org/en-US/docs/Web/API/Response

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM