2016-05-09 4 views
23

ポリフェルをフェッチしてURLからJSONまたはテキストを取得する場合、レスポンスがJSONオブジェクトであるかどうかを確認する方法を知りたいフェッチのレスポンスがjavascriptのjsonオブジェクトであるかどうかを確認する方法

fetch(myRequest).then(response => { 
    const contentType = response.headers.get("content-type"); 
    if (contentType && contentType.indexOf("application/json") !== -1) { 
    return response.json().then(data => { 
     // process your JSON data further 
    }); 
    } else { 
    return response.text().then(text => { 
     // this is text, do something with it 
    }); 
    } 
}); 

あなたはコンテンツが有効なJSON(ドンであることを絶対に確認する必要がある場合は」:それはthis MDN exampleに示すように、あなたは、応答のcontent-typeをチェックすることができる唯一のテキスト

fetch(URL, options).then(response => { 
    // how to check if response has a body of type json? 
    if (response.isJson()) return response.json(); 
}); 
+0

ます。http:// stackoverflowのを.com/a/20392392/402037 – Andreas

答えて

44

ですヘッダーを信頼しないでください)、常に応答をとして受け入れることができますそしてそれを自分で解析:

fetch(myRequest) 
    .then(response => response.text()) 
    .then(text => { 
    try { 
     const data = JSON.parse(text); 
     // Do your JSON handling here 
    } catch(err) { 
     // It is text, do you text handling here 
    } 
    }); 

を非同期/

をお待ちしておりますがasync/awaitを使用している場合は、あなたがより直線的にそれを書くことができます:

async function myFetch(myRequest) { 
    try { 
    const reponse = await fetch(myRequest); // Fetch the resource 
    const text = await response.text(); // Parse it as text 
    const data = JSON.parse(text); // Try to parse it as json 
    // Do your JSON handling here 
    } catch(err) { 
    // This probably means your response is text, do you text handling here 
    } 
} 
関連する問題