Reputation: 23
I'm using Nodejs, expressjs, sqlite3.
I have managed to get my data from database and route using expressjs, this is all in a js file called server.js
Now I want to send/use the data I have extracted in the front end.
I tried to have a global variable and use that global variable in other js files but that didn't work. After some research, I see AJAX most of the time. Do I need to use AJAX to send my data from backend to frontend?
The idea is to update frontend based on what product the user selects. I get the product data in server js, I don't know how to send it to frontend to fill in tables and change name of product based on the data on the database.
Also, should I continue and see if saving/using my data in a global variable works? Thanks.
Upvotes: 1
Views: 8115
Reputation: 240
Use a WebSocket
WebSocket is probably the way to go: https://socket.io/
from backend you just need to emit the payload
Upvotes: 0
Reputation: 637
AJAX is a great way to request data from the back end without triggering a full page reload. However it adds a layer of complexity that it doesn't sound like you need. Since you're using express you get access to a templating engine out of the box that can handle this for you.
The express response object has a render method where you specify the template to use, and the data to send to the template. Some pseudo code for you:
// server.js
app.get('someroute',(req,res,next)=>{
//get data from DB, returns promise
return db.getData().then((data)=>{
return res.render('myTableTemplate',data);
});
});
In the template file, you would populate the table with the JSON data appropriately.
If you are using a client side JS library (react, vue, angular, etc.) you can skip res.render(...)
and simply res.json(data)
Upvotes: 2
Reputation: 287
You should create RESTful APIs to do what you want. This means you have to use AJAX and you can't work with global varibles.
Upvotes: 0