Home > Back-end >  why does the fetch request not work when I try to fetch a markdown file?
why does the fetch request not work when I try to fetch a markdown file?

Time:03-16

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.

CodePudding user response:

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.
}
  • Related