HTML file not loading js file (NodeJS + Express) - javascript

I am running a NodeJS server that serves static files in my public directory. However, my javascript file, main.js, does not run. Below is my code. Any help would be much appreciated.
app.js
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
main.js
function main() {
console.log('test');
};
document.addEventListener('DOMContentLoaded', main);
index.html
<!doctype html>
<html>
<head>
</head>
<body>
<script src="javascripts/main.js"></script>
</body>
</html>
directory structure:
app.js
public
index.html
javascripts
main.js

Related

How to use javascript methd from external files in hbs file

Let's say i have a simple project, index.html and one .js file with a method:
<!DOCTYPE html>
<html lang="pl">
<HEAD>
<script src="controller.js"></script>
<meta charset="utf-8"/>
<title>Project</title>
</HEAD>
<body>
<textarea id ="someID" name = "textFieldName"></textarea>
<button onclick="showNewData()">Button</button>
<p id="score"></p>
</body>
</html>
function getText(){
value = document.getElementById('someID').value;
}
function showNewData(){
getText();
document.getElementById('score').innerHTML = "Current data: "+value;
}
I tried to do the same on localhost:3000. So i've done npm project with express and hbs dependencies. It start from server.js file:
const express = require('express');
const port = 3000;
const app = express();
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port);
In "views" folder i have hbs file looked the same like former index.html file but it can't use javascript method from external file. Does anyone know how to do that?
in hbs file
As far as the browser knows, it is HTML. Clients do not care, and cannot know, if an HTTP response is generated by reading a static file or dynamically with some form of server side processing.
src="controller.js"
The value of the src attribute has to resolve to a URL containing the JavaScript
app.get('/', (req, res) => {
res.render('index')
})
The only URL your web server knows about (and so will provide anything other than a 404 error for) is /.
If you want /controller.js to provide a JS file then you need to write code to make that happen.
How to handle static files is covered in the Express Getting Started Guide.

How can I include a script element in a Handlebars template?

So I'm trying to create a client-side JavaScript file for one of my .hbs templates. But it doesn't seem to even load the .js file when i add a tag in the html code. I have looked around for a solution but I can't find any clear answer for handlebars, at least not one I can understand.
I have tried:
specifying type="text/javascript"
adding the tag in main.hbs right below {{{body}}} just to see if it works but nothing happend.
Playing around with the .js file but it clearly doesn't get executed.
booking-functions.hbs
console.log("test")
document.addEventListener("DOMContentLoaded", function(){
console.log("In bookingfunctions")
// bunch of code
})
booking.hbs
<div>
<script src="../functions/booking-functions.js"></script>
// Bunch of html that works fine with handlebars
</div>
```
main.hbs
======
```
<!DOCTYPE html>
<html lang="en">
<head>
// Nothing javascript or handlebars related here
</head>
<body>
// Navbarcode and such
//Login check with #if handlebars
{{{body}}}
</body>
</html>
app.js
const path = require('path')
const express = require('express')
const expressHandlebars = require('express-handlebars')
const variousRouter = require('./routers/various-router')
const accountRouter = require('./routers/account-router')
const bookingRouter = require('./routers/booking-router')
const app = express()
//Session code here
// Setup express-handlebars.
app.set('views', path.join(__dirname, 'views'))
app.engine('hbs', expressHandlebars({
extname: 'hbs',
defaultLayout: 'main',
layoutsDir: path.join(__dirname, 'layouts')
}))
// Handle static files in the public folder.
app.use(express.static(path.join(__dirname, 'public')))
//body parser middleware
app.use(express.json());
app.use(express.urlencoded({extended:false}));
// Attach all routers.
app.use('/', variousRouter)
app.use('/accounts', accountRouter)
app.use('/booking', bookingRouter)

How to serve html in express.js that references js file from server and run it on client side?

I'm trying to write simplest possible server that serves html page with client side scripts.
Already tried based on http://expressjs.com/en/starter/static-files.html,
Using express.js to serve html file along with scripts, css, and images and
How to load JS file in html using express server, but still I don't get it.
File structure I'm using:
node_modules
resources
resources/page.html
resources/script.js
index.js
package.json
index.js:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(__dirname + '/resources'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname , 'resources', 'page.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
Content
</body>
<script scr="script.js"></script>
</html>
script.js:
var i = 0;
setInterval(() => {
if (i < 10) {
console.log(i);
i++;
}
}, 100);
I type in google chrome browser address localhost:3000/ and page is successfully loader ("Content" string is displayed), but script script.js is not running (empty console). I expect browser to retrieve script.js file and print numbers to console when page.html is loaded.
In the page.html file, change the property scr to src in the script tag and it will work.

Why am i getting a 404 js file, while including a script tag?

index.html
<head>
<script src="/main.js"></script>
</head>
Error:
GET http://localhost:3000/main.js
Structure
Project
app.js
view
index.html
main.js
I've tried src="main.js". /view/main.js
Very basic, but dont want to get stuck on this any longer... sigh.
if it helps my app.js file has this:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/view/home.html');
});
So, according to your comments - you are serving only the 'index.html' file instead of whole directory.
Try this code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'view')));
//... other settings and server launching further
If you want to set serving static files to particular route - extend 'app.use' line with '/your-route', like this:
app.use('/your-route', express.static(path.join(__dirname, 'view')));
After that you can use <script src="main.js"></script> in your index.html

javascript not loading in HTML file - nodejs + expressjs

I am new to nodejs and expressjs so Im trying to build simple web app to grasp both frameworks.
Here I have built a project with the following architecture:
js
test.js
views
index.html
server.js
my server file looks like this:
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var ejs = require("ejs");
var server = express();
server.use(server.router);
server.use(express(__dirname));
server.set('view engine','html');
server.engine('html', require('ejs').renderFile);
server.get("*", function(request, response){
response.render('index.html');
});
server.listen(port, host);
and my index file like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Starter Template for Bootstrap</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script language="javascript" src="/js/test.js" type="text/javascript"></script>
</head>
<body ng-app>
<div class="container">
<div class="starter-template">
some code
</div>
</div><!-- /.container -->
</body>
</html>
My index.html file loads properly but I cannot get the test.js file to load. How can I fix this?
Use express.static built-in middleware function in Express.
Add this line after server.engine. This mechanism should allow static files to be served e.g. images, javascripts, css
app.use(express.static(__dirname + '/js'));
Now you can load:
http://localhost:1337/js/test.js
change render into sendfile and move your js folder to public folder then add this middleware
server.use(express(__dirname+'/public'));
JS files are rendered as static files.
Ref: https://expressjs.com/en/starter/static-files.html
First create a folder "static" and keep .js files in it.
Now, correct the script tags of these .js files in .ejs file.
in the nodejs side :
var path = require("path");
app.use(express.static(path.join(__dirname + '/js')));//middleware
in the HTML page :
<script src="./my_script.js"></script>
As this files is static, you should add the entire root directory to 'app'.
Like this:
app.use(express.static(path.join(__dirname, '/')));
So that you can quote all of your files by relative path.

Categories