Problems running imported JS in EJS file - node.js

I made an express Nodejs server and set the static folder.
The CSS has access to the page, but the JS does not find any elements. Everything is NULL.
app.use(express.static(__dirname + '/static'))
app.get('/', (req, res) => {
res.render('index')
})
//test from clientside index.js
document.body.append('test')
<script src="js/index.js"></script>
<link rel="stylesheet" href="style/main.css">
What am I doing wrong?

Problem
DOM doesn't load yet when your JS runs. It's not related to EJS, that's just how every script works.
Solution
Add defer attribute
<script defer src="js/index.js"></script>

Related

Azure app uploads from VSCode without linking static sources

I have an incredibly basic node.js server test app running on port 3000 in VSCode. The server appears to work via node on localhost or deployed to Azure, and hosts an index.html file. I have clients happy to talk to it.
/* Server.js */
const express = require('express');
const app = express();
app.use(express.json());
app.get("/", function(request, response){
response.sendFile(__dirname + "/index.html");
});
app.post("/", function(request, result){
console.log(request.body["itema"] + " " + request.body["itemb"]);
result.send("Pong!!");
});
app.listen(3000, function(){
console.log("Server started on port 3000");
});
<!-- Index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Simple App</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<h1>Test!</h1>
</body>
</html>
/*style.css*/
h1 {
color: tomato;
}
Azure Configuration Settings
The index.html links to a css file which doesn't appear to be linked when deployed. I've tried deploying the app to azurewebsites.net through VSCode, however I'm seeing the same results. Only index.html is present in the sources view. I get an error claiming it can't render the source it didn't find.
"Refused to apply style from https://<appname>.azurewebsites.net/style.css because its MIME
type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is
enabled."
If I view the advanced page (.scm.azurewebsites.net), again I can see only index.html.
Index only
But .scm.azurewebsites.net/wwwroot/ shows me the css file has been uploaded correctly.
Index and linked sources
I'm convinced it'll be a simple solution to someone and that the PATH variables will need to be set...somehow... but I've hit a brick wall and my Google-Fu has finally been exhausted.
Thanks!
Adding the following to server.js resolved the issue.
app.use(express.static("./"));
This is further explained here and is required in express to serve static files.
https://expressjs.com/en/starter/static-files.html

How to add static file from `node_modules` after declare the `public` as static in express?

In my express app, I am keeping the below config:
var express = require("express");
var path = require("path");
var jsonServer = require("json-server");
var app = express( );
app.use(express.static('public'));
app.get("/", function( req, res ) {
res.sendFile( express.static( path.join(__dirname, "/public/index.html" ) ) );
});
app.use('/api', jsonServer.router('./db.json'));
app.listen( 3000 );
All this is works fine. the problem is, I am not able to add the jquery from node_modules. here is my HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Promise Defined</title>
<script src="node_modules/jquery/dist/jquery.js" type="text/javascript"></script> //not working sibling folder of public
<link rel="stylesheet" href="styles/app.css"> //works fine. inside public folder
</head>
<body>
<h1>New Title</h1>
</body>
</html>
What is the correct way to fix this? or how to handle this kind of scenario?
Thanks in advance.
node.js does not serve any files by default (unlike some other web servers). So, if you want node_modules/jquery/dist/jquery.js to work, then you have to either make sure that your express.static() line of code will include that file or you have to define a route specifically for that file. Also, it is sometimes dangerous to use a relative path with no leading / because that makes it relative to the path of your page which is generally not necessary and can make things difficult if you want to serve the same file in lots of different pages on your site.
For example, you could do this in the web page:
<script src="/jquery.js" type="text/javascript"></script>
And, this:
app.get("/jquery.js", function(req, res) {
res.sendFile(path.join(__dirname, "node_modules/jquery/dist/jquery.js"));
});
Personally, I would probably move jquery.js to a public/scripts directory on my server so I'm not serving anything out of the node_modules directory, so all my publicly served files are centralized in one place so it's entirely clear what can be served to a client and what cannot and so I could design one or two express.static() statements to serve all my public files.

How can I serve mp3 file on node js?

I am building simple web app that if the user press button, it will make sound(mp3 file in the server side).
//html file
<script>
function playSound () {
document.getElementById('play').play();
}
</script>
<body>
<audio id='play', src='http://127.0.0.1:1337/', type='audio/mpeg'
<button onclick='playSound()' class='btn btn-danger btn-circle btn-lg'>
<i class='fa fa-5x fa-fire'>
</body>
//app.js
app.get('/music.mp3', function(req, res){
ms.pipe(req, res, "/music.mp3");
});
It works if I insert online source in audio attribute, but it does not serve my local server file. How can I fix this?
Thanks in advance!
To serve static files such as images, CSS files, and JavaScript files, audio, use the express.static built-in middleware function in Express.
app.use(express.static('public'));
I've already answered such type of question. See this answer

Provide an HTML page with JS with node.js and express

I am trying to serve an html page with a linked js script using node.js and express.
This is the server that provide the page:
var express = require("express");
var app2 = express();
app2.get('/', function(req, res) {
res.sendfile('./index.html');
});
app2.listen(process.env.VCAP_APP_PORT || 3000);
and this is the page:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Demo</h1>
<script src="/js/socket.io.js"></script>
<script src="/js/codice.js"></script>
</body>
As you can see I have two js scripts in my js folder but they are not loaded when I launch the page. What can I do?
What you would normally do is place any public resources (JavaScript files, CSS files, images etc) in a directory (Express names it public by default) and then use the express.static middleware in your app.configure call:
app.configure(function () {
// Various other middleware functions...
app.use(express.static(path.join(__dirname, "public")));
});
This effectively runs a static file server which will return any file inside the public directory. Currently, your browser is making a request for your JS files, but the Express server doesn't know what to do with them. They will eventually time out.
If you generate the initial state of your app with the global express executable (available if you installed Express via npm globally), it will set most of this up for you.

node.js - can't load my files with express3

I am using express3 and when I'm trying to load my html/javascript/css files it loads the html without the css.
I'm using this code to load the files -
express.get('/', function (req, res) {
res.sendfile("index.html");
res.sendfile("style.css");
res.sendfile("script.js");
});
So what can I do?
First, link the css and javascript to the page via tags in the header of your HTML
<link rel='stylesheet' href='/path/to/style.css' />
<script src='/path/to/javascript.js'></script>
Be sure that you're using the static middleware in your app.use() section, this will tell Express where to find your static files.
app.use(express.static(__dirname + '/public'));
Now, your Express app should serve your static css and js files.
You link to css and javascript from the html page...
Try looking at the static files example app in the express github repo: https://github.com/visionmedia/express/tree/master/examples/static-files
Basically you make another http request for static files (.js, .css)

Resources