Javascript does not work on Nodejs

Asked

Viewed 500 times

0

I have an html page that takes some functions of a Javascript page, but when I open this page by Nodejs javascript does not work. I did the test with simple Javascript and Jquery commands, but both work only if I open my HTML directly

    alert("carregado alerta");



    $(document).ready(function() {
        $('#idQueIdentificaP').text('JAVASCRIPT ALTEROU ESSE P')
      });
      
      
      function alterar(){
      $('#idQueIdentificaP').text('JAVASCRIPT ALTEROU ESSE P DE NOVO')
      }
<html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
  
        <script type="text/javascript" src="mudartexto.js"></script>
        <title>"Meu html </title>
   </head>

    <body>
        <h1> Pagina</h1>

        <p id="idQueIdentificaP"></p>   
        <button type="button" onclick="alterar()">alterar de novo</button>
        <script type="text/javascript" src="mudartexto.js"></script>

    </body>
</html>

call code on Node:

app.get("/pag", function(req,res){
    
    res.sendFile(__dirname + "/html/index.html");
})

2 answers

0


Use the express.static

const express = require('express')
const app = express()

app.use(express.static("public"))

app.get("/", (req, res) => {
  res.sendFile(__dirname+"/public/index.html")
})

app.listen(7005, () => {
  console.log("server running on 7005")
})
  • Thank you, it worked perfectly.

0

Just to explain why express.static worked. The browser makes a request to the server and the server returns the index.html according to the code:

app.get("/", (req, res) => {
  res.sendFile(__dirname+"/public/index.html")
})

When receiving html the browser interprets the code and v that needs to load more file as <script type="text/javascript" src="mudartexto.js"></script>, then make another request to the server requesting the file upload mudartexto.js, in this case the express.static solves why the file is in the public folder, incidentally I believe that only the express.static nor does it need the app.get since index.html tbm is in the folder public

Browser other questions tagged

You are not signed in. Login or sign up in order to post.