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>
Related
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 trying to use express-handlebars and use partials but I am getting the following error message
The partial header could not be found.
My app.js code looks like as follows.
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'hbs');
app.get('/', function (req, res) {
res.render('home');
});
app.listen(3000);
This is all working and the express app is running on localhost:3000.
My folder structure is as follows:
|_app.js
|_views_
|_home.hbs
|_layouts_
|_main.hbs
|_partials_
|_header.hbs
main.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>
header.hbs
<nav>
Home
Contact
</nav>
home.hbs
{{> header}}
<h1>Hey world!</h1>
Everything works as expected until I try and introduce header.hbs as a partial.
Can anyone see any issue with my code?
Following further investigation I have also tried this, without any success:
// Create `ExpressHandlebars` instance with a default layout.
var hbs = exphbs.create({
// Uses multiple partials dirs, templates in "shared/templates/" are shared
// with the client-side of the app (see below).
partialsDir: [
'views/partials/'
]
});
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
I believe you are missing the next line:
exphbs.registerPartials(__dirname + '/views/partials');
It was necessary to define the following settings for express-handlebars partials to work.
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');
Here is the complete code:
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');
app.get('/', function (request, response) {
response.render('home');
});
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 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');
}
Im having some trouble including a html snippets into my index.html .
I have tried to follow, the ejs documentation but I just can't seem to make it work.
Directory Structure:
project
-public
--assets
---css
---images
---js
--Index
---index.html + index.css and index.js
--someOtherPageFolder
-views
--partials
---partials1.ejs
--index.ejs
--layout.ejs
-server.js
This is my server.js (NEW):
var express = require("express");
var partials = require("express-partials");
var http = require('http');
var path = require('path');
var app = express();
app.get("/", function(req, res) {
res.redirect("index");
});
app.configure(function(){
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
This is my test.ejs:
<h1>This is test!</h1>
And this is where I want the html snipp to go:
<div id="sb-site">
<div class="">
<p>Not test</p>
<%- include test.html %>
</div>
</div>
What am I doing wrong?
Is there also a way for me to do this and use .html instead of .ejs (Im using eclipse and it doesn't support .ejs files)
With include you shoud do like this:
<%- include ("./partials/footer") %>
Express 3 breaks ejs partials, use express-partials instead.
// Include it like so with your other modules
var express = require("express");
var partials = require('express-partials');
var server = express();
// Finally add it into your server conviguration
server.configure(function(){
server.set('view engine', 'ejs');
// Include partials middleware into the server
server.use(partials());
});
In your .ejs views, enjoy the luxury like so...
<%- include ../partials/header %>
<section id="welcome">
Welcome
</section>
<%- include ../partials/footer %>
Also, rather than setting the ejs module to read .html just follow this answer to get eclipse to render .ejs as .html. how do i get eclipse to interpret .ejs files as .html?
As an example, this is how a basic express structure is setup...
project
--public
--views
----layout.ejs
----index.ejs
----partials
------partial1.ejs
--server.js
server.js would look like...
var express = require('express'),
partials = require('express-partials'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3838);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Middleware
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
Your route would look like...
server.get("/", function(req, res) {
res.render("index");
});
And finally, your layout.ejs...
<html>
<head>
<title></title>
</head>
<body>
<%- body %>
</body>
</html>
and index.ejs ...
<div id="index">
<%- include partial1.ejs %>
</div>
If you need a reference to the working example, here it is
You need to use the new include syntax:
before: <%- include test.html %>
after: <%- include ('test') %>