0

I am using marked js to render a string containing markdown text to html div.
index.html

...
<div id="myDiv"></div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="index.js"></script>
...

index.js

...
function renderMarkdown() {
    let myDiv = document.querySelector('#myDiv');
    myDiv.innerHTML = marked.parse('# This is heading \n ## This is heading 2 \n ### This is heading 3 \n Let us write a quick text and sign off! Here is a list \n - Hello \n - World')
}

async function getMarkdownFile() {
    const response = await fetch('./content/hello.md', {
      method: 'GET',
    })
    .then(response => response.text())
    .then(data => {
      console.log(data);
    })
}
...

The markdown renders inside myDiv as expected.
enter image description here

I also have a folder in the same directory containing a bunch of markdown files. But, I am unable to import/use them in index.js file. I tried using fetch but, get this error:

enter image description here

As it is evident, it becomes very difficult to edit and read larger strings. Is there any better way to render markdown to the html (maybe by importing a markdown file)?
PS: I am using Vanilla Js.

onapte
  • 217
  • 2
  • 8
  • Where is the example from the files that do NOT work? – mplungjan Mar 13 '22 at 13:04
  • How can I import those files in Vanilla js? – onapte Mar 13 '22 at 13:05
  • you can use Fetch? – mplungjan Mar 13 '22 at 13:07
  • Used that but not working. I will update the question with the example. – onapte Mar 13 '22 at 13:08
  • See my updated answer – mplungjan Mar 13 '22 at 13:11
  • There's no point in using `then` with `async/await`. It sort of defeats the purpose of using `async/await` in the first place. – Andy Mar 13 '22 at 13:19
  • Using `fetch` gives a network error but using `xmlHttpRequest` does not. But, `Cross Origin Request Blocked` pops up when using any of these methods. – onapte Mar 13 '22 at 13:27
  • Also, am I not understanding something. You're already successfully reading in markdown and converting it. Why are you suddenly get CORS errors when you're doing the same thing? This won't have anything to do with file size. – Andy Mar 13 '22 at 13:28
  • Can we use `fetch` to access file /folder in the same directory? I don't have this hosted. – onapte Mar 13 '22 at 13:31
  • "Can we use `fetch` to access file /folder in the same directory? I don't have this hosted"—only if you make those files available via HTTP. Client-side JavaScript runs in the user's browser and has no access to your server's filesystem (or the user's, for that matter). – ChrisGPT was on strike Mar 13 '22 at 13:38

0 Answers0