fetch(url)
console.dir(fetch);
fetch( url, { method: '', headers: { 'Content-Type': 'application/json' }, body: '' } ) .then( res => res.json() ) .then( res => { console.log( 'success ', res ) } )
根据请求的数据类型,返回的结果分别有:
fetch('https://glpla.github.io/utils/data/rank/20240203.json') .then(res => res.json()) .then(res => console.log(res))
fetch('./tmp.txt') .then(res => res.text()) .then(res => console.log(res))
fetch('../../common/drill.html') .then(res => res.text()) .then(res => { document.getElementById('require').innerHTML = res; })
fetch('https://glpla.github.io/utils/avatar/avatar0.png') .then(res => res.blob()) .then(res => img.src = URL.createObjectURL(res))
https://png.pngtree.com/recommend-works/png-clipart/20250101/ourmid/pngtree-cartoon-deer-standing-png-image_14982249.png
fetch('https://png.pngtree.com/recommend-works/png-clipart/20250101/ourmid/pngtree-cartoon-deer-standing-png-image_14982249.png', { headers: { 'Accept': 'image/png' } }) .then(response => response.blob()) .then(blob => { const url = URL.createObjectURL(blob); img.value = url; console.log(img.value); }) .catch(error => console.error('Error:', error));
fetch('https://codilime.com/') .then(response => { if (!response.ok) { throw Error(`HTTP error: ${response.status}`); } return response.json(); }) .then(console.log) .catch((err) => { console.log(err.message) });
ok: true redirected: false status: 200 statusText: "OK" type: "cors" url: "http://localhost:3000/clerk/2002"
ok: false redirected: false status: 404 statusText: "Not Found" type: "cors" url: "http://localhost:3000/clerk/2002"
fetch('/utils/data/cart.json') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }) .finally(() => { console.log('Fetch operation completed.'); });