2016-05-09 11 views

Odpowiedz

44

można sprawdzić na content-type odpowiedzi, jak pokazano na this MDN example:

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

Jeśli chcesz mieć absolutną pewność, że treść jest ważna JSON (i don” t ufaj nagłówkom), zawsze możesz po prostu zaakceptować odpowiedź jako text i analizować to sam:

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

asynchroniczny/czekają

Jeśli używasz async/await, można napisać go w bardziej liniowo:

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 
    } 
} 
Powiązane problemy