[solved] Call server.js functions from index.html

EDIT Solved, thank you!!

Short version:
How do I call functions defined in server.js in index.html and client-side js functions?

Long version:
My goal is to have a site user input an ID on index.html, cross-check that info with a simple database (currently using lowdb) and return the user’s information associated with that ID. Since it seems I can’t use lowdb on the client side, I was wondering how I could access functions defined in server.js in index.html and client-side js?

I have experimented with doing something like this on the server side:

app.get("/test", (request, response) => {
console.log(“test”);
var informationToReturn = 1234;
//return informationToReturn?
})

but I’m not sure how to then return a value so the client side can use it.

Apologies if this is a simple question!!

I suggest using ejs. Then do res.render("file",{req,informationToReturn)}

1 Like

Hey @xluo1,

So far what you’ve done is correct.

It is possible to return the value by using res.send(). So your code should be

app.get("/test", (request, response) => {
   console.log(“test”);
   var informationToReturn = 1234;
   response.send(informationToReturn);
});

Then in your HTML file (or your client-side JS file), you can make a GET request using the Fetch API:

fetch("/test")
  .then(res => res.text())
  .then(data => {
     // do stuff with the data you returned
     console.log(data);
   });
1 Like

Big problems with this is that all client data is super easy to get, which allows for anyone to get access to all your client data. Probably not the best of ideas.

Not really, CORS can block external requests that are not from the same domain.

I’m sure one could use the console to bypass it. With the right tools & knowledge it won’t be that hard.

Yes, it’s not too hard. Plus, there’s no such thing as CORS if you’re making a request from Node.js using a package like node-fetch, although that can also be prevented by using another package named (surprise, surprise!) cors.