簡體   English   中英

使用fetch檢查內容

[英]Checking for content using fetch

我正在使用fetch來進行返回JSON數據的API調用。

有時,API調用返回狀態OK ,內容為null 我依靠檢查狀態來獲取內容,但這給了我一個錯誤,因為沒有JSON數據。

我得到的錯誤是: Uncaught (in promise) SyntaxError: Unexpected end of JSON input

這是我的典型獲取模式,顯然我需要通過添加一個JSON數據檢查來改進它。 我該怎么修改呢?

export const getSomeData = () => {

    return (dispatch) => fetch('/api/myapifunction', fetchOptionsGet())
        .then((response) => {
            if(response.ok) {
                // I need to add logic here to check for JSON data before calling parseJSON
                parseJSON(response)
                .then(data => {
                    // Do something
                })
            } else {
                // Failed
                // Handle failure
            }
        })
}

我為fetchOptions創建了函數,例如GET或POST以及parseJSON。 它們功能簡單。 這就是parseJSON的樣子:

export const parseJSON = (response) => {
    return response.json();
}

據我了解,response.json()只是一個承諾,不一定是數據。 如何檢查我是否收到任何JSON數據?

這里的訣竅是你的服務有點雙重。 它說它OK ,但后來根本沒有發送字節。 JSON.parse('')拋出相同的錯誤。

您可以使用catch作為Dekel注釋來解決此問題,或者您可以使用response.text()

if (response.ok) {
  response.text()
    .then(text => text && text.length ? response.json() : Promise.resolve({}))
    .then(data => { // here you'll need to handle an empty object

這基本上檢查返回的字符串值。 如果沒有返回任何內容,它將為您提供一個空對象而不是拋出錯誤。 這將有助於區分由於數據錯誤而導致的JSON解析錯誤,而根本沒有數據。

如果瀏覽器能夠將響應的內容解析為有效的json .thenresponse.json() promise將正確運行並進入.then部分。

如果它無法這樣做 - 您可以使用.catch來查看問題所在:

parseJSON(response)
    .then(json => {
        // Do something with the json data
    }).catch( reason => {
        // response is not a valid json string
    })

暫無
暫無

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

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