1
I’m a beginner in the Node world, and I’m having trouble relating a . js file to an HTML.
I took a simple code, in it I have a combobox that is filled when pressing a button:
//app.js
var express = require('express');
var app = express();
app.get('/', (req, res)=>{
res.sendFile('page.html', {root:__dirname});
});
app.listen(3000);
This is the code I want to put in HTML:
//page.js
document.getElementById("btnCarregar").onclick = function () {
var comboCidades = document.getElementById("cboCidades");
var opt0 = document.createElement("option");
opt0.value = "0";
opt0.text = "";
comboCidades.add(opt0, comboCidades.options[0]);
var opt1 = document.createElement("option");
opt1.value = "scs";
opt1.text = "São Caetano do Sul";
comboCidades.add(opt1, comboCidades.options[1]);
var opt2 = document.createElement("option");
opt2.value = "sa";
opt2.text = "Santo André";
comboCidades.add(opt2, comboCidades.options[2]);
var opt3 = document.createElement("option");
opt3.value = "sbc";
opt3.text = "São Bernardo do Campo";
comboCidades.add(opt3, comboCidades.options[3]);
};
And the related HTML:
<head>
</head>
<body>
<form action="#" method="post">
<p>
<select id="cboCidades"></select>
</p>
<p>
<input type="button" id="btnCarregar" value="Carregar combobox" />
</p>
</form>
<script src="page.js"></script>
</body>
So...if I start the server, and access localhost:3000, the page loads normally, but the button doesn’t work because it can’t use the . js external and browser console keeps popping up that message:
But...if I just open the HTML file the button works normally.
I’d like to understand why it doesn’t work when accessing localhost:3000 and what possible solutions.
From now on, thank you for your attention.
Thank you! For a brief moment I thought it was not necessary to statically serve the files, because on all the sites where I searched they implied that I should simply pass the directory of . js in the tag script.
– SpockWayne
Good morning, one of the advantages I see on express is that if you do not set in the settings, it does not, this goes for body, headers, static files, Sponse, status code, etc.
– Chance