A
A
atumbochka2021-03-26 13:07:41
JavaScript
atumbochka, 2021-03-26 13:07:41

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..."))

In it, I created like and I want this constant to be identified on the second page, that is, so that I can refer to it or do something with it in the second file:
let likeStatus

document.addEventListener("DOMContentLoaded", async function() {
    let res = await fetch("http://localhost:8080/")
    let json = res.json()
    likeStatus = json.like
    alert(likeStatus)
})

In general, it displays the following for me: Uncaught ReferenceError: require is not defined
What does I know about the existence of modules, but I need it through fetch and, as far as I understand, this can be done, but I have no idea how. I googled my question and didn't find anything.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-03-26
@vabka

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..."))

After that, the code from the frontend will work fine.
Uncaught ReferenceError: require is not defined

Are you sure you are running this on a node, and not in a browser?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question