From ee3f72b9d1a35a48998710dfbf62fa136170da6d Mon Sep 17 00:00:00 2001 From: "Rico Sta. Cruz" Date: Fri, 3 Jun 2016 19:34:43 +0800 Subject: [PATCH] Update fetch() --- js-fetch.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/js-fetch.md b/js-fetch.md index 93b90d7e9..b5b7b1c06 100644 --- a/js-fetch.md +++ b/js-fetch.md @@ -37,11 +37,34 @@ fetch('/data.json', { headers: { 'Accept': 'application/json' - } + }, + + credentials: 'same-origin', // send cookies + credentials: 'include', // send cookies, even in CORS + }) ``` -## +### Catching errors + +Non-2xx responses are still successful requests. Use another function to turn them to errors. + +```js +fetch('/data.json') + .then(checkStatus) +``` + +```js +function checkStatus (res) { + if (res.status >= 200 && res.status < 300) { + return res + } else { + var err = new Error(response.statusText) + err.response = response + throw err + } +} +``` ## Using with node.js