Node JS loading js & css file in an ejs file - javascript

My folder is like so :
server.js
app
--routes.js
views
--ace-builds-master
--\src-noconflict
--ace.js
--index.ejs
So in 'views' is my ace editor stuff and my index.ejs file.
I want to call ace.js in my index.ejs file. Do I need to create an app.get in my express routes like below?
app.get('/ace', function (req, res) {
res.sendFile('\ace-builds-master\src-noconflict\ace.js');
});
And in my ejs file do I write it like so:
<script src="/ace" type="text/javascript" charset="utf-8"> </script>
I receive a "GET http://localhost:8080/ace" when loading in browser

Ejs renders the view file,view can access your static folder .You can make your ace folder as static . It will be loaded when view load
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Load static files
app.use(express.static(path.join(__dirname, 'ace')));

just use
<script src="../ace" type="text/javascript" charset="utf-8"> </script>
instead of
<script src="/ace" type="text/javascript" charset="utf-8"> </script>
because when server loads ejs it makes a virtual folder inside the public folder
so you just need to go one step back.

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.

Rendering HTML file with res.sendFile() in Express.js

I'm trying to render my HTML file with some a local CSS file, local JS file and two remote files as links
but all I got is a plain HTML in the browser
here is the top of my HTML file (index.html):
<script src="src/drawflow.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="src/index.css" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
/>
This is my server code (app.js):
"use strict";
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(__dirname + "/src"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.listen(process.env.port || 4000, () => {
console.log("listening to port 4000...");
});
and here is my file structure:
file structure
The index.html file is working just fine when opened in the browser but it can't be fetched properly from the server.
Any ideas ?
Thanks to the comment by Chris Short
I replaced
app.use(express.static(__dirname + "/src"));
to
app.use('/src', express.static(path.join(__dirname + '/src')));
and it worked perfectly.
Thanks a lot.
If I'm understanding correctly. The assets for your HTML file are not being fetched properly, so your HTML is showing as bare when you access through the browser. With this understanding, the reason your assets are not loading properly is due to the way your app.js is set up.
Currently you are trying to access href="src/index.css" in your header, however all of your assets are going to be found from your website root. Expressjs handles all app.use statements as middleware and by default are attached to the root of your website. If you would like to have this accessible from "src" then you will need to set up your express.static a bit differently like so.
app.use("/src", express.static(path.join(__dirname, "/src"));
See the below for more info
https://expressjs.com/en/starter/static-files.html
https://expressjs.com/en/guide/using-middleware.html

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

Simple error including Javascript files into a test app using basic MEAN example

I'm taking a course (on MEAN) and it starts by trying to get something running end-to-end. The point now is to add in the Javascript necessary to make Angular work. I'm having some kind of simple problem including the scripts.
The error I'm getting is (firebug), which appears to complain about the entire index.html file, is:
The Jade code is short. It is an index.jade file which extends a layout.jade file which includes in all the js files:
extends ../includes/layout
block main-content
section.content
div(ng-view)
h2 some regular text 5
This produces the following index.html file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/vendor/toastr/toastr.css">
<link rel="stylesheet" href="/css/site.css">
</head>
<body ng-app="app">
<script type="text/javascript" src="/vendor/jquery/jquery.js"></script>
<script type="text/javascript" src="/vendor/angular/angular.js"></script>
<script type="text/javascript" src="/vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="/vendor/angular-route/angular-route.js"></script>
<script type="text/javascript" src="/app/app.js"></script>
<section class="content">
<div ng-view></div>
<h2>some regular text 5</h2>
</section>
</body>
</html>
================ UPDATE ========
It appears Node is substituting the index.html file for the assets. The project directory structure is:
The server.js file which node runs is:
var express = require('express');
var stylus = require('stylus');
// set env variable to determine if in production or development mode; this contains environment if set my MODE
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// create express application
var app = express();
function compile(str, path) {
return sytle(str).set('filename', path);
}
// configure express
//app.set('views', __dirname + '/server/views');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(stylus.middleware({
src: __dirname + '/public',
compile: compile
}));
console.log("dirname:" + __dirname);
app.use(express.static(__dirname + '/public'));
//app.use(express.static(path.join(__dirname, '/public')));
app.get('/partials/:partialPath', function(req, res) {
res.render('partials/' + req.params.partialPath);
});
app.use(express.logger('dev')); //- logger no longer bundled with Express
app.use(express.bodyParser());
// add routes:
// We won't tell the server specifically what routes to handle. We'll have the client-side be
// responsible to server up and 404 notices. Client-side will have to specify all routes.
// Other solution is to coordinate your routes, so that every client route is also listed on the server.
// Far more customary to have a server side have a catch all that lists up a 404 page.
app.get('*', function(req, res) {
res.render('index');
})
var port = 3030;
app.listen(port);
console.log("listening on port: " + port + " ...");
This looks like a path issue as the page is not able to access your assets directory. Make sure your public folder is set right in your node server code. It should be along the lines of app.use(express.static(path.join(__dirname, 'public_folder_name')));. Looking at your folder structure, your server.js is nested in server folder and not at the same level as your public folder. Try app.use(express.static(__dirname + '/../public'));

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