-
-
Save xudaolong/98ad318ecb38af9abf52b23d2f1dd1fe to your computer and use it in GitHub Desktop.
JavaScript-Fetch 优雅使用|-|&tag=Other
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from 'isomorphic-fetch'; | |
// usage : const { status, data, error } = yield fetcher('/api/url'); | |
export default function fetcher(url, options = {}) { | |
return new Promise((resolve) => { | |
fetch(url, Object.assign({}, { | |
credentials: 'same-origin', | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
}, options)) | |
.then(response => { | |
const status = +response.status; | |
response.json() | |
.then(data => resolve({ status, data })) | |
.catch(error => resolve({ status, error })); | |
}) | |
.catch(error => resolve({ error })); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment