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

336
Visualizações
Call JS function in html on server side (nodejs)

I have an index.html

    <!DOCTYPE html>
<html>
    <head>
        <title>Server-side Example</title>
        <script src="./CircleArea.js"></script>
            </head>
    <body>
        <input
        id="ftpd"
        type="button"
        value="Calculate"
        onclick="CircleArea()"
        />
    </body>
</html>

It calls the CircleArea.js file.

const PI = 3.14
let radius = 3;

    function circleArea(){
         var inputField = document.createElement("INPUT");
         inputField.setAttribute("type", "text");
         inputField.setAttribute("value", (PI*radius*radius));
         document.body.appendChild(inputField);
    }
    
    module.exports ={circleArea}; // This I added for nodejs

It works fine. But I now want to run Index.html on the server-side.

I added server.js

let http = require('http');
let fs = require('fs');

let handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    fs.readFile('./Index.html', null, function (error, data) {
        if (error) {
            response.writeHead(404);
            respone.write('Whoops! File not found!');
        } else {
            response.write(data);
        }
        response.end();
    });
};

http.createServer(handleRequest).listen(8000); 
console.log('Server running at http://localhost:8000');

Now node server.js

gives error

CircleArea.js:1 
        
       Uncaught SyntaxError: Unexpected token '<'
(Index):13 
        
       Uncaught ReferenceError: CircleArea is not defined
    at HTMLInputElement.onclick ((Index):13:6)

My question is how should I modify Index.html and CircleArea.js to run it on nodejs?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code has nothing to do with server-side evaluation. You're using Node.js as a web server. The server doesn't evaluate the client code. It doesn't import CircleArea.js. You don't need

module.exports ={circleArea}; // This I added for nodejs

and should remove it. It's a CommonJS module export and not allowed in browser code.

A web browser sends a request for index.html. The server responds with the content of Index.html. The browser evaluates it. It finds a script tag for ./CircleArea.js and sends a request for this file. The server responds with the content of Index.html because there is no routing in the server. Open the dev tools in your browser to see the problem. The server responds with the same data (the content of Index.html) for all requests. You have to implement routing.

let http = require('http');
let fs = require('fs');

let handleRequest = (request, response) => {
  let file = 'Index.html';
  if (request.url === '/CircleArea.js') {
    file = 'CircleArea.js';
    response.writeHead(200, {
      'Content-Type': 'application/javascript',
    });
  } else {
    response.writeHead(200, {
      'Content-Type': 'text/html',
    });
  }
  fs.readFile('./' + file, null, function (error, data) {
    if (error) {
      response.writeHead(404);
      response.write('Whoops! File not found!');
    } else {
      response.write(data);
    }
    response.end();
  });
};

http.createServer(handleRequest).listen(8000);
console.log('Server running at http://localhost:8000');

This is a very basic and simple solution. You can use it for a very simple routing. For a more complex routing I recommend a framework like Nest.js

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