express remove prefixed URL to public folder - node.js

Even though i have created static public folder in app.js
when i navigate to "http://localhost:3000/calenders/add" and i don't get any styles which is in public folder. because express has added "calenders/add/" to the public folder URL.
So it looks like "http://localhost:3000/calenders/add/content_inside_public".
But the correct URL should be "http://localhost:3000/content_inside_public"
Navigate to app index works fine and load all the styles.
Of course i can set static path in app.js like this
app.use('/calenders/add',express.static(__dirname + '/public'));
but it's not practical if i have many routes in my app.
I believe this is happening because i have a separated folder called partials inside the view directory to store headers,footers and navigation bar, so that i can include them any where in the app easily without writing same html code again and again.
This is how i included them in calender/add.ejs
<!DOCTYPE html>
<html>
<% include ../partials/head.ejs %>
<body>
<!-- Side Navbar -->
<% include ../partials/side_nav.ejs %>
<div class="page">
<!-- navbar-->
<% include ../partials/header.ejs %>
<% include ../partials/footer.ejs %>
</div>
</body>
</html>
This is how i have access the folders and style-sheets inside the public directory in headers.ejs and footers.ejs
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/popper.js/umd/popper.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="js/grasp_mobile_progress_circle-1.0.0.min.js"></script>
<script src="vendor/jquery.cookie/jquery.cookie.js"></script>
<script src="vendor/chart.js/Chart.min.js"></script>
This is my project structure.
/public
/css
/js
/vendor
.......
/routes
calendars.js
control_panel.js
index.js
/views
/calendars
add.ejs
/control_panel
index.ejs
calendars.ejs
/partials
header.ejs
footer.ejs
......
index.ejs
Here is the app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', index);
app.use('/users', users);
app.use('/control_panel', control_panel);
app.use('/calenders', calenders);
Calendars.js
router.get('/add', function(req, res, next) {
res.render('calenders/add', { title: 'Express' });
});
control_panel.js
router.get('/', function(req, res, next) {
res.render('control_panel/index', { title: 'Express' });
});

This has nothing to do with express,
this is because in /calenders/add, src of <script src="vendor/jquery/jquery.min.js"></script> will resolve to http://localhost:3000/calenders/add/vendor/jquery/jquery.min.js,
because vendor/jquery/jquery.min.js is a relative path.
what you need is to change the url to this:
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/popper.js/umd/popper.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/js/grasp_mobile_progress_circle-1.0.0.min.js"></script>
<script src="/vendor/jquery.cookie/jquery.cookie.js"></script>
<script src="/vendor/chart.js/Chart.min.js"></script>

Related

Express only serving css file in main page

I am learning node and using expressjs the problem is that the css file is only working on the main page and not any other page following is the code for the app:
var express = require("express");
var app = express();
// assets
app.use(express.static("public"));
// simple file testing
app.get("/anything/:stuff", function(req, res){
var stuff = req.params.stuff;
res.render("love.ejs", {stuff: stuff});
});
// posts page
var books = [
{title:"Harry Potter",author:"JK Rowling",editions:7},
{title:"Peere Kamil",author:"Humaira Saeed",editions:4},
{title:"Mushaf",author:"Abdullah khan",editions:2}
];
app.get("/books", function(req, res){
res.render("books.ejs",{books:books});
});
app.listen(3000, process.env.IP, function(){
console.log("Serving Now!");
});
The following is the code for the page where it is not working.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="app.css" />
<title>demo app</title>
</head>
<body>
<h1>You fell in love with : <%= stuff %> </h1>
<%
if(stuff.toUpperCase() === "WAQAS"){ %>
<P>GOOD CHOICE HE IS THE BEST</p>
<% } %>
<p>P.S This is the love.ejs file</p>
</body>
</html>
The file is under public directory.
Use an absolute URL for the CSS file, so the browser doesn't look for it relative to the current URL:
<link rel="stylesheet" href="/app.css" />
Explanation: say that you open the URL /anything/helloworld in your browser. When your HTML contains just app.css, without the leading slash in front of it, the browser will try and load /anything/app.css (because without that slash it's relative to the current URL), which doesn't point to your CSS file.
When you add the leading slash, express.static will be able to find the CSS file in public/.

ng-view not working with partials in AngularJS/Express

Everything was working until I tried to display a partial file in ng-view.
/public/app/app.js
angular.module('app', ['ngResource', 'ngRoute']);
angular.module('app').config(function($routeProvider,$locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {templateUrl: '/partials/main', controller: 'mainCtrl'});
});
angular.module('app').controller('mainCtrl', function($scope){
$scope.myVar = "Hello Angular";
});
/server/includes/layout.jade
doctype html 5
html
head
link(rel="stylesheet", href="/css/bootstrap.css")
link(rel="stylesheet", href="/vendor/toastr/toastr.css")
link(rel="stylesheet", href="/css/site.css")
body(ng-app="app")
block main-content
include scripts
/server/includes/scripts.jade (version number are not in the script)
script(type="text/javascript", src="/vendor/jquery/jquery.js") 2.1.0
script(type="text/javascript", src="/vendor/angular/angular.js") 1.2.16
script(type="text/javascript", src="/vendor/angular-resource/angular-resource.js")
script(type="text/javascript", src="/vendor/angular-route/angular-route.js")
script(type="text/javascript", src="/app/app.js")
/views/index.jade
extends ../includes/layout
block main-content
section.content
div(ng-view)
/views/partials/main.jade
h1 This a Partial
h2 {{ myVar }}
and finally server.js
var express = require('express'),
stylus = require('stylus');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str, path){
return stylus(str).set('filename', path)
}
app.configure(function (){
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static (__dirname + '/public'));
});
app.get('/partials/:partialPath', function (req, res){
res.render('partials/' + req.params.partialPath);
})
app.get('*', function(req, res) {
res.render('index');
});
var port = 3030;
app.listen(port);
console.log('Listening on port' + port + '…');
Directory structure:
When I launch the 'node server.js' and go to 'localhost:3030', I get a blank page instead of "This is a Partial Hello Angular" with this HTML:
<!DOCTYPE html 5>
<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">
<section class="content">
<div ng-view="ng-view"></div>
</section>
<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></body></html>
In the tutorial this config works perfectly, but when I run it, the ng-view is empty. Any idea why?
EDIT:
Node.js runs like a charm. Something must have changed in the conf or I forgot something. In the tutorial everything was installed with bower like I did, and the javascript, hrefs were pointing to /vendor/ in the public directory and it seemed like it worked.
When I looked in the Javascript console, I got this error message for all scripts: SyntaxError: Unexpected token '<' which < is the beginning of an HTTP error message.
So I copied all the called files with error into /vendor/ change the url in "/server/includes/scripts.jade" like "/vendor/jquery/jquery.js" to "vendor/jquery.js" and it worked.
But I feel like I applied a patch. With bower, shouldn't it work with the previous settings?
Not sure how much this will help but I notice all the bower packages are in the 'bower_components' directory. That is the default for bower unless you specify another directory. So, if you want the bower components installed say, '/public/vendor', do the following:
1) create a file called ' .bowerrc ' and save it in your root directory ie. with gitignore, bower.json, etc.
2) in the file put:
{
"directory": "public/vendor"
}
That will load the bower components where you want them. The file ' .bowerrc ' is a config file for bower and you can find the guidance at: http://bower.io/
HTH
Thers is something off in your app.js file. Replace it with this and you should be good to go:
var app = angular.module('app', ['ngResource', 'ngRoute']);
angular.module('app').config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});
});
angular.module('app').controller('mainCtrl', function($scope){
$scope.myVar = "Hello Angular";
});
app.get('*', function(req, res,next) {
if(req.xhr != true)
{
res.render('index');
} else
{
next();
}
});
modify like this

ejs include function can not find the template with html extension

My ejs engine set up is app.js is like below:
// this parse html file as ejs file
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/view');
My directory is like this:
view (folder)
home.html
head.html
app.js
Home.html is like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>home</title>
<% include head %>
</head>
<body>
</body>
</html>
and head.html is like this:
<link rel="stylesheet" type="text/css" href="css/main.css">
<script type="text/javascript" src="js/jquery-1.5.js"></script>
the problem is the file head.html will not be parsed if the extension was html. Error says it expect ejs file. So there is a problem with include function?
As Elie Gnrd is suggesting, you use .ejs files directly by changing the view engine configuration of Express.
If that isn't an option, and you want/need to keep using .html as an extension for your templates, you have to be explicit in the include:
<% include head.html %>
You can use .ejs files directly by using app.set('view engine', 'ejs'); and renaming index.html to index.ejs.
Here is an example:
http://robdodson.me/blog/2012/05/31/how-to-use-ejs-in-express/
arrr ;)
you did not mention what app - so I assume Express >=3
solution : forget the dot and __express in
app.engine('.html', require('ejs').__express);
It should read :
app.engine('html', require('ejs').renderFile);
change html file with ejs
-view
--home.ejs
--head.ejs
-app.js
set app view engine like
app.set('view engine', 'ejs');
make index.ejs for main file and include home.ejs and head.ejs in index.ejs
<%- include('head')%>;
<%- include('home')%>;
and render it app.js like
app.get('/', (req, res) => {
res.render('index');
});
cmiiw..
I too had this problem and modified this file of my app:
myapp/node_modules/ejs/lib/ejs.js
The function is:
function resolveInclude(name, filename) {
var path = join(dirname(filename), name);
var ext = extname(name);
if (!ext) path += '.ejs';
return path;
}
You can change the default extension or as in my case I changed the function to a more direct:
function resolveInclude(name, filename) {
return join(dirname(filename), name) + '.html';
}
They can modify the function as they wish.
I hope that is helpful.

Express & EJS - layout.ejs not used

Im trying out EJS as a view engine with Express. It seems that my layout.ejs is not used. I have two views index.ejs and layout.ejs both in my 'views' folder. It seems that index.js is rendered but layout.ejs is not. The layout.ejs file should be including a CSS file but when the page is rendered in the browser this is not there. Any test test text that I place in the layout.ejs file is not output with the response.
Am I missing an additional configuration step?
Thanks!
My server.js code:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);
In my layout.ejs I am linking to a single css file which resides in the public folder.
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<div id="container">
index.html
</div>
Here's the module you need:
https://www.npmjs.org/package/express-ejs-layouts
Do the following:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));
Now the ejs engine should use your layout.
app.set('view options', { layout:'layout.ejs' });
Place layout.ejs into your views folder.
Alternately you can place layout.ejs into views/layouts folder and then use
app.set('view options', { layout:'layouts/layout.ejs' });
I have a similar issue. In my case I would rather use Jade but I have a requirement for a more "html" style template engine for a particular project. At first I considered express-partials or ejs-locals (as mentioned in a comment by Jonathan Lonowski) or even using html via the pipe or dot syntax within Jade templates (see here for more information about that option and this SO post). I am not able to introduce the additional dependencies for express-partials and ejs-locals into this project. These two projects do look good and might meet your needs.
If you do not want to use these projects, you can do something like the following:
views/layout-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
views/layout-foot.ejs
</body>
</html>
views/index.ejs (or any other page)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>
routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}
This is not an optimal solution but it works. Most of my application will be a single page app and I have some other restrictions I have to work within so this works for my needs. This may not the best solution in many cases - especially if you have complex and/or changing layouts.

Can not get CSS file

My directory set up is like this :
app.js
vews
home.html
css
style.css
My home file is like this :
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
</body>
</html>
My app is like this :
var io = require('socket.io'),
url = require('url'),
sys = require('sys'),
express = require('express'),
http=require('http');
var app = express();
var server = http.createServer(app);
var socket = io.listen(server);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('home');
});
app.listen(4000);
sys.puts('server running ' + 'now ' + Date.now());
The problem is when i run the app, css file can not be loaded.
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
So your final directory structure should look like this
app.js
views
home.html
public
css
style.css
And do not forget to require path module
var path = require('path')
In one of my apps, I have these relevant files in this file structure:
/
index.js
/public
/stylesheets
main.css
/views
/partials
header.ejs
The index.js includes app.use(express.static(path.join(__dirname, '/public')));
Note the /public.
The header.ejs partial includes <link rel='stylesheet' type='text/css' href='/stylesheets/main.css' />
Note the lack of public, it’s implied by the middleware.
In your example, your current directory for static files doesn’t match where you are keeping static files.
Try this:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
This might solve the problem.

Resources