In my example, I'm trying to fetch data from the server and save it to the document as text in the <p> element. Everything works fine except that the appendChild method doesn't seem to work as it should. Here is a sample of my code and the error message:
(async () => {
let resp = await fetch("/shaders", {
method: "GET"
});
let txt = await resp.text();
let elm = document.createElement("p").innerHTML = txt;
console.log(txt) // Hello Stack Overflow!
// logs the message as expected
document.body.appendChild(elm)
// error occurs
})()
With error message: Uncaught (in promise) TypeError: Node.appendChild: Argument 1 is not an object, at line 10.
Does anyone know what is causing this problem?
--
Note: With the append method it works just fine
CodePudding user response:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// i use json placeholder api just for test you can keep your default methode to get data
(async () => {
let resp = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => data.title)
let txt = await resp;
let node = document.createElement("p")
let elm = document.createTextNode(txt)
node.appendChild(elm)
document.body.appendChild(node)
})()
</script>
</body>
</html>
CodePudding user response:
The Fetch API for CORS is deprecated, fetch must use a http or https link.