I do not have a separate server code and I keep getting a cors error.
I have the below code:
muggle_process.js
file:
let url = "https://favqs.com/api/qotd";
let saveButtonElement = document.querySelector("#save-username");
let nameInputElement = document.querySelector("#username");
let welcomeMessage = document.querySelector("#welcome-message");
let quoteOfTheDay = document.querySelector("#quote-of-the-day");
let author = document.querySelector("#author");
saveButtonElement.addEventListener("click", function () {
let name = nameInputElement.value;
if (name.length < 2) {
quoteOfTheDay.innerText = "";
welcomeMessage.innerHTML = "Please enter at least 2 letters.";
}
else {
nameInputElement.value = "";
welcomeMessage.innerText = `Welcome, ${name}!`;
fetchingQuote();
}
});
function fetchingQuote() {
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
quoteOfTheDay.innerHTML = "<label>Quote of the day</label><br>" + data.quote.body;
author.innerHTML = "---" + data.quote.author;
})
.catch((err) => {
alert("Error: " + err);
console.log("Error", err);
});
}
document.getElementById("go-back").onclick = function () {
location.href = "welcome.html";
};
document.addEventListener("keyup", function (event) {
if (event.key === "Enter") {
saveButtonElement.click();
nameInputElement.value = "";
}
});
When I run the code, I keep getting the below error in my console browser:
Access to fetch at 'https://favqs.com/api/qotd' from origin 'http://127.0.0.1:5500' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
I also tried adding headers “Access-Control-Allow-Origin
“, but still keep getting the cors error. How can I fix this error?
My file structure is as below for the application: