Ask coding questions

← Back to all posts
How do I connect a node.js project to a html project
Mathman05 (1)

I want to be able to get a value from the node.js project and display it on the website. I've been trying with express(node.js) and fetch(Javascript) how do I get them to not throw an error and give me the information I want?

Comments
hotnewtop
Mathman05 (1)

just found it: app.use(require("cors")()); it just wanted this one line server side |:

R2D2VaderBeef (8)

Here is code that should get your data:

async function getData() {

const options = {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          },
        };
const response = await fetch('https://discbottest-2.mathman05.repl.co/', options);
const resdata = await response.json();
console.log(resdata); // resdata is now a JSON object with the response
}
getData();

This will not work on a different repl unless the response has a particular header: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin

Mathman05 (1)

@R2D2VaderBeef putting a .catch(console.error); on the fetch tells me an error: "TypeError: Failed to fetch"

R2D2VaderBeef (8)

@Mathman05 Are there any other errors?

R2D2VaderBeef (8)

@Mathman05 What if you don't use the .catch? Does it just not do anything?

Mathman05 (1)

@R2D2VaderBeef .catch only runs if it gives an error, and yes it does nothing.

Mathman05 (1)

More info: I'm trying to get information from https://discbottest-2.mathman05.repl.co but it can't seem to get it other node.js projects can see the information but javascript always errors