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

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.

Related

Problems running imported JS in EJS file

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>

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.

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)

node.js app can't find socket.io

I installed socket.io in the app directory (along with express) and in the index.html file I link to it this way:
<script src="http://localhost:8080/node_modules/socket.io/lib/socket.io.js"></script>
I get a 404 on this request. I double-checked the link and it's fine. the node.js app runs on port 8080 and I have no idea why it doesn't work
UPDATE:
Apparently it is something to with Express. When not using it I don't have that problem and socket.io works fine.
This is he setup of my server file:
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.listen(8000);
and this is the front-end:
<script src="/socket.io/socket.io.js"></script>
<script src="js/vendor/jquery-1.8.3.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
Also, I switched the jQuery from google CDN to local and it doesn't find it too
Make sure you've made socket.io listening to external connections in your back-end. Basically socket.io has inside method of providing your socket.io.js file, so you should place your require ('socket.io').listen(app) before defining any routes to your app.
The correct url is :
<script src="/socket.io/socket.io.js"></script>
as randunel said.
So, your configuration should look like this :
UPDATED for express 3.x :
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app).listen(8000);
require('socket.io').listen(server); // Your app passed to socket.io
Server-side
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
Don't use that whole path, it does not correspond to your project's directory structure. Just use
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
By the way, make sure that socket.io is also listening on 8080, not just the other services in your project.
Try putting your JS file in http://localhost:8080/javascripts/socket.io.js, basically the JavaScript directory of your public folder.
The way is the one from randunel.
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
If you link the file directly, you can get a "Welcome to socket.io" message instead of the file.
There's also a CDN socket.io.js file available to link, but it's outdated and will not work fine on new projects, so it's not recommended.

Resources