Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
how to pass data from express server to javascript function directly on page load?

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"});
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda