Answer the question
In order to leave comments, you need to log in
How does fetch work?
I want to say in advance that I am a complete zero in the server side of js, but I know standard js with cycles, functions, objects and do not deny that what I wrote is complete nonsense.
How does fetch work? Naturally, I first looked at the documentation and videos on YouTube, but I didn’t understand anything, that is, it returns some (exactly what?) Data from the page where I make the request. What can it return at all: just text from the page or some DOM elements? And for some reason everyone wraps the response in JSON.
I have a file server:
const like = false
const http = require("http")
http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(`
<h1>HELLO</h1>
`)
}).listen(8080, () => console.log("Server is on..."))
let likeStatus
document.addEventListener("DOMContentLoaded", async function() {
let res = await fetch("http://localhost:8080/")
let json = res.json()
likeStatus = json.like
alert(likeStatus)
})
Answer the question
In order to leave comments, you need to log in
const like = false
const http = require("http")
http.createServer((req, res) => {
//Видимо сначала надо вернуть с сервера значение like.
res.writeHead(200, {"Content-Type": "application/json"});
res.end(`
{ "like": ${like} }
`); // Не шарю в ноде, так что вот так накостылял
}).listen(8080, () => console.log("Server is on..."))
Uncaught ReferenceError: require is not defined
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question