I am building an API for my site that grabs an MD
file based off URL param (?key=test.md) and then renders it with Marked.js
.
My problem is after the API grabs the file and trys to render it i get this error
marked.min.js:6 Uncaught Error: marked(): input parameter is undefined or null
Please report this to https://github.com/markedjs/marked.
at ie.parse (marked.min.js:6:34386)
at Object.oe (marked.min.js:6:35545)
at main.js:14:30
I've checked my variables and network and don't have an idea of what is undefined. Here is m current API code and simple workings.
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
let article = urlParams.get('key');
let pre = `https://mrchaoticx.github.io/Chaotic-Club/articles/${article}`;
let contentID = document.getElementById("content");
let content;
fetch(pre)
.then(response => response.text())
.then(data => {content = data})
.then(data => console.log(content))
contentID.innerHTML = marked.parse(content);
<div class="content" id="content">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/14.1.2/marked.min.js" integrity="sha512-bXyBT2/sYjZg1D7ykDS6eJSE4DFDVPJHvbRAfdfYKr6IusrCz7wAmSm36vz9G8zMob25Rvqu90vft3JI71ygcQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
The issue here is that the fetch
kicks off a Promise chain that resolves with a value after the rest of the code after it has already completed. You are passing an undefined content
value to the marked.parse
function.
let contentID = document.getElementById("content");
let content; // <-- (1) declared & undefined
fetch(pre) // <-- (2) start Promise chain
.then(response => response.text())
.then(data => {content = data}) // <-- (4) have content now
.then(data => console.log(content));
contentID.innerHTML = marked.parse(content); // <-- (3) pass undefined
Move the DOM mutation into the Promise chain to be used when you have fetched the markdown content.
Example:
fetch(pre)
.then(response => response.text())
.then(content => {
console.log(content);
const contentID = document.getElementById("content");
contentID.innerHTML = marked.parse(content);
});