Is there a way to send data from the server to a client-side JavaScript file without displaying it on the main screen using the innerHTML
property?
https://i.sstatic.net/YcsJq.png
I've gone through several express.js tutorials but haven't found a method to add data to the client-side JS file.
This is the process I'm looking for:
[open the webpage] -> [(in server) get data from database] -> [send data to client-side js file] -> // do more stuff in the client-side
Any suggestions on how to solve this issue?
Here's my current code:
// Makes display the client-side html, temporary disabled.
// app.use(express.static('client'));
// Queries
const QUERIES = {
prev: 'SELECT * FROM en.prevstore',
curr: 'SELECT * FROM en.currstore',
next: 'SELECT * FROM en.nextstore',
samp: 'SELECT * FROM en.sample'
}
// Create connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'en'
});
// Router
app.use('/', (req, res) => {
db.query(QUERIES.samp, (err, results) => {
let ternary = err ? console.error(err) : res.json(results);
})
})
Client-Side HTML (request from the comment)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="quotes">
should be filled as quotes of data from database
</div>
<div class="color">
should be filled as color of data from database
</div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Client-Side JS:
function getWord() {
fetch('http://localhost:4000')
.then(res => res.json())
.then(({data}) => console.log(data))
}
getWord() // I know it won't work but tried for just in case.