2016-05-09 6 views
23

Ich benutze Fetch Polyfill, um einen JSON oder Text von einer URL abzurufen, möchte ich wissen, wie kann ich überprüfen, ob die Antwort ein JSON-Objekt oder ist Text ist es nurWie überprüfen, ob die Antwort eines Abrufs ein JSON-Objekt in Javascript ist

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

Antwort

44

Sie für die content-type der Antwort überprüfen könnten, wie in this MDN example gezeigt:

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 
    }); 
    } 
}); 

Wenn Sie absolut sicher sein, dass der Inhalt gültig JSON (und don‘ist t die Header zu vertrauen), können Sie die Antwort immer einfach alsakzeptierenund analysieren Sie es selbst:

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/erwarten

Wenn Sie async/await verwenden, können Sie es in einer linearen Art und Weise schreiben:

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 
    } 
}