I want to pass data from express server to javascript function directly, how do I do it?
my html file
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="main.css" />
<script type="text/javascript" src="main.js">
</head>
<body>
<h1> I want to display message sent by server with js function in main.js, not with <%= msg %> </h1>
</body>
</html>
my main.js
window.addEventListener('load', function() {
console.log('All assets loaded');
get_data();
});
function get_data() {
fetch('./',
)
.then(function(response) {
return response.text();
})
.then(async function() {
console.log("data passed by html is: ")
console.log(msg) //msg is sent by express server
});
}
my express index.js (using ejs)
app.get('/', function(req, res){
res.render("main.html",{msg:"hello"});
});
You can add a script tag to you HTML and render Javascript code:
<script>
const msg = "<%= msg %>";
</script>
Make sure you add this script tag before your main.js script tag. The msg constant should then be available globally in your Javascript code.
Although this answers the question, I don't recommend it. If you need to use a value from your backend in your frontend code you should fetch it from an endpoint.