Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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"});
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda