I use an express app to serve an static pre-compiled jade file. which includes a external javascript file. but its not loaded while the page gets loaded. but i can access the javascript by the express static/public url. Why its not loading on the html?
app.js
var express = require('express'),
path = require('path'),
sass = require('node-sass');
var app = express();
/* default configurations */
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
/* routes */
app.get('/', function(req, res) {
res.send('Hello World');
});
app.get('/home', function(req, res) {
res.render('index.html');
});
module.exports = app;
index.html
<body>
<script type="text/javscript" src="/scripts/site.js"></script>
<script type="text/javascript">
window.onload = function() {
Site.View.init();
}
</script>
</body>
site.js
var Site = Site || {};
Site.View = {
init : function() { alert('view'); }
};
When i open the page in browser i get ReferenceError: Site is not defined
Thanks.
Add app.use('/public/js', express.static(path.join(__dirname, '/public/scripts'))); to app.js, in order to indicate the subfolders of the pulic folder;
If it still not works, change src="/scripts/site.js" to src="/public/scripts/site.js";
site.js must be inside public/scripts from your root directory.
I am not sure but both views and express static pages are gone to public directory in your code.
Use default configuration as:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
You may also add a route for it like this:
app.get('scripts/site.js', function(req, res){
res.send('./scripts/site.js');
}
Related
Here is my directory
enter image description here
newTab.jade code
doctype html
html
head
title New Tab
link(rel = 'stylesheet', type = 'text/css', href = '/public/index.css')
body
p hello world
index.css code
p{
background-color: black;
color: white;
}
app.js code
const express = require('express');
const app = express();
const port = 3000;
app.locals.pretty = true;
app.listen(port, function(){
console.log("Server Connected port: "+port);
});
app.set('view engine', 'jade');
app.set('views', './views');
app.get('/', function(req, res){
res.render('newTab');
});
jade file can't loading css file.
I tried
href = "/public/index.css"
but it doesn't work too.
Append a middleware to Express to serve static files too.
In your app.js file:
// require path module to join your public folder with __dirname
const path = require('path');
//...
app.get('/', function(req, res){
res.render('newTab');
});
app.use('/', express.static(path.join(__dirname, 'public')));
There are more things express.staticcan do. E.g. setting the maxAge for caching purpose:
// 31557600000ms = 1 year
app.use('/', express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
suggestion
try
doctype html
html
head
title New Tab
include index.css
body
p hello world
on your newTab.jade file
and include index.css on views directory
So I'm working on developing a Node/Express webapp for basic CRUD operations and I'm having a hard time implementing Handlebars within the project.
When I try to use handlebars none of my stylesheets from my .hbs (previously .html) pages are loading.
Here's the file tree:
Here is the error:
And here is an example of the script import statements from
index.hbs
<!-- Bootstrap -->
<link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
And Finally here is the server.js file
var express = require('express'),
bodyParser = require('body-parser'),
path = require('path'),
mysql = require('mysql'),
dbconfig = require('./config/database'),
exphbs = require('express-handlebars');
var connection = mysql.createConnection(dbconfig.connection)
connection.query('USE ' + dbconfig.database);
var app = express();
//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//Set static path
//app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static(__dirname + '/public'));
//app.set('views', __dirname + '/views');
//app.use('/views', express.static(path.join(__dirname, '/views')));
app.engine('hbs', exphbs({defaultLayout: false}));
app.set('view engine', 'hbs');
app.set(express.static(__dirname + '/public'));
//app.use('/views/vendors', express.static(path.join(__dirname, '/views/vendors')));
//app.use(express.static(__dirname + '/public/vendors'));
app.get('/', function(req, res) {
res.render('index');
connection.query("SELECT * FROM Student", function(err, rows){
console.log(rows);
});
});
app.listen(80, function() {
console.log('we are live on 80');
});
I tried using various static paths from other things I found on SO but wasn't able to get any of them to work.
Any help would be greatly appreciated!!
Thanks!
Fixed my problem by adding the following line above my app.get('/'....
app.use("/vendors",express.static(__dirname + "/vendors"));
app.use("/build",express.static(__dirname + "/build"));
app.use("/images",express.static(__dirname + "/images"));
app.get('/', function(req, res) {
I think that can be possible that the problem is in the handlebars configuration, please look at a configuration like this:
app.engine('.hbs',exphbs({
defaultLayout:'layouts',
layoutsDir:path.join(app.get('views'),'layouts'),
partialsDir:path.join(app.get('views'),'partials'),
extname:'.hbs',
helpers: helpers
}));
app.set('view engine','hbs');
maybe in yours it would be:
app.engine('hbs', exphbs({defaultLayout: false, extname:'.hbs',}));
if you are usign app.set(express.static(__dirname + '/public'));
try to put in the public folder your styles for example the bootstrap folder, and then all you have to do is call it in this way:
<link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
I am a newbie to node and express and I am really stuck right now. I want to load a custom script.js form the public folder but it doesnt seem to load. Nothing in the network tab, no errors in the console. When I to go the url: localhost:3000/javascripts/script.js, I am seeing the code. I tried every answer given on SO, but nothing seems to work. Using the express generator. What am I doing wrong here.
See code:
app.js
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
index.ejs file
<html>
<head>
<!-- include head -->
<% include partials/head.ejs %>
</head>
<body>
<% include partials/header.ejs %>
<% include partials/footer.ejs %>
<script scr="/javascripts/script.js"></script>
</body>
</html>
index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
<script scr="/javascripts/script.js"></script>
should be
<script src="/javascripts/script.js"></script>
I am really new to the whole MEAN-stack and are trying to create an application on openshift but are unable to render a new page.
I just keep getting this error and can't solve it with anything I've googled.
My Error: Failed to lookup view "/register" in public directory
It works completely fine to render the index page with app.get('/', func()) in server.js and tried to to the exact same thing with app.get('/register). I used to have the same problem with '/' at first but solved it using app.use(express.static(__dirname + '/public'));
Both index.html and register.html are located in the public directory.
These are extracts of my code:
index.html
<body ng-app="">
<div class="container" ng-controller="LoginController" >
<h1>Logg in</h1>
<input class="form-control" placeholder="ID"/>
<input class="form-control" placeholder="Password"/>
<button class="btn">Logga in</button>
<button ng-click="open()" class="btn">Register User</button>
</div>
</body>
logincontroller
function LoginController($scope, $http) {
console.log("Hello from Login");
$scope.open = function () {
console.log('open i login.js');
$http.get('/register')
};
};
server.js
var express = require('express');
var fs = require('fs');
var mongojs = require('mongojs');
var jade = require('jade')
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.get('/env',function(req, res){
res.json(process.env);
});
app.get('/', function (req, res) {
res.render('/index', {});
});
app.get('/register', function (req, res) {
res.render('/register');
});
app.set('view engine', 'jade');
There are a couple of issues.
1) Don't use a slash for the 'register' file. This is a file in the /public folder, not a folder or route.
app.get('/register', function (req, res) {
res.render('register');
});
2) You have set jade as your rendering engine. This means you will be serving .jade files. Your public folder should have index.jade. And it should look like this:
html
body(ng-app='')
.container(ng-controller='LoginController')
h1 Logg in
input.form-control(placeholder='ID')
input.form-control(placeholder='Password')
button.btn Logga in
button.btn(ng-click='open()') Register User
A couple of notes:
Jade is a HTML templating engine, it's relatively straight forward, see http://jade-lang.com/tutorial/.
There is express-generator which will give you an example app, it's an excellent starting point: http://expressjs.com/en/starter/generator.html
By the way, there is also an HTML-2-Jade converter, I find this helpful sometimes: http://html2jade.org/
I write a simple program which is really unreadable. At first, I didn't know how to use template so I decide, in spite of that, to write html code inside my node.js code.
(solved)
Try something like this
I usually have a project structure like:
lib
node_modules
public (This is where the CSS and page JS goes)
routes
views (This is where you put your EJS templates)
app.js
In your package.json make sure you have included ejs
"ejs": "*"
In app.js (assuming you use express)
var express = require("express");
var app = express();
var routes = require("./routes/routes.js");
//Other setup code
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//Here is an example HTTP route
app.get('/home', routes.view_page);
//Other Server code
And then in routes.js
exports.view_page = function (req,res){
var customMessage = "Hello, Node is awesome";
res.render("view", {
msg:customMessage
});
};
I think your .ejs file is fine, this is a very minimal express server that works with your example:
app.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var customMessage = "My Message";
res.render('view.ejs', {msg:customMessage });
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
then use your view.ejs and put it in the sub-folder views/