I am trying to display a markdown file from my computer to the browser window with fetch, but the response (text) is undefined, why is this happening? I leave a codepen with my code.
https://codepen.io/matiasConchaSoto/pen/popvQgp
<main> <h1>Blog con Markdown y ShowDown</h1> </main> <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/2.0.3/showdown.min.js"></script> <script> const d = document, $main = d.querySelector("main"); fetch("./assetsPropios/javascript.md") .then(res => { console.log(res); res.ok ? res.text() : Promise.reject(res); }) .then(text => { console.log(text); $main.innerHTML = text; }) .catch(err => { console.log(err); let message = err.statusText || "OcurriĆ³ un error"; $main.innerHTML = `Error ${err.status}: ${message}`; }); </script>
somebody help me please.
Advertisement
Answer
The first .then()
has a missing return
.
Try:
return res.ok ? res.text() : Promise.reject(res);
Even better, something like:
if(res.ok) { return res.text(); } else { throw new Error(res.statusText); // or some message of your own choice. }