I am new to node.js and am having trouble successfully referencing or "calling" a js file that I have in the "public" folder in one of my views with the EJS template engine.
My current folder structure is as follows:
In my .ejs file, just before the closing body I have the following. Where url is actually __dirname, since I have passed it as a parameter from res.render()
<script src="<%= url + "/js/alert.js" %>"></script>
This alert.js is for testing and should just run an alert (but it doesn't):
alert("POR FIN FUNCIONA!");
I am working locally, so in the browser my path is: "http://localhost:5000/"
But if I do a console.log(__dirname) the result is the path inside my machine, that is, "C:\Users\xxxxx\Documents\Programming web\Control-finances" and not "http://localhost:5000 /".
If I try to access the resource in question by accessing "http://localhost:5000/js/alert.js" I can see it in the browser, but I cannot place that route statically in the .ejs since when uploading it to a real server will not work. I need a way to dynamically print "http://localhost:5000" if I'm local or the "final url" when the project is already uploaded to a server.
I also leave you my app.js in case it can be of help. You will see that in the console.log() I have done some tests with little things that I have found on the internet but none of them work. I have commented what each of those console.log() returns.
const express = require("express");
const app = express();
const port = 5000;
console.log(__dirname); //C:\Users\xxxxx\Documents\Programación web\Control-finanzas
app.set('view engine', 'ejs'); //Motor de plantillas EJS
app.set('views', __dirname+'/views'); //Directorio que contiene las vistas
const server = app.listen(port, () => {
console.log("# El servidor ya esta a la espera de peticiones del cliene por el puerto", port);
});
console.log(server.address().address); //"::"
console.log(server.address().port); //5000
const os = require("os");
console.log(os.networkInterfaces().Ethernet[1].address); //192.xxx.x.xx (he censurado con x por precaución)
console.log(os.hostname()); //PC_de_Pepito (nombre de mi máquina. Adulterado, sí)
app
.get("/", (req, res) => {
console.log(res.header.host); //undefined
res.render("dashboard", {titulo: "Dashboard", url: __dirname});
})
/* aquí van otros .get() irrelevantes que omitiré */
.use(express.static(__dirname + "/public"))
.use((req, res, next) => {
console.log("### Use 404");
res.status(404).sendFile(__dirname+"/public/404.html"); //Curiosamente aquí si que me muestra la pagina adecuada e incluyo "/public/" en la ruta, de otro modo no funciona
})
Many thanks for your time! (:
There are several things you have to keep in mind, one of them is that you have to resolve the __direname so you don't run into problems. Another thing is that you should instantiate the configurations before requesting any route and not chain the methods as it would have different/unexpected results. He left the code of how I would do it:
and in the template simply enough with:
Now, if it is absolutely essential to send a route (or any other variable) it is better to send it directly from the controller, it is the controller's responsibility to send all the data and not the view's to calculate anything.
controller:
View (or template):