I'm trying to develop a Blog with NodeJS. I found a nice HTML blog theme, and put all files to views folder. This is the content of app.js
var express = require('express'),
app = express(),
cons = require('consolidate');
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
//app.use(express.static(__dirname + '/views'));
app.use(express.bodyParser());
// I'm using Express 3, not 4.
app.use(app.router);
app.get('/', function(req,res){
res.render('index', {menu_items:[{"link":"#","text":"TXT"},{"link":"#","text":"TXT"}]});
});
app.listen(3000);
This code is rendering index.html and also rendering menu_items in index.html . But it's not rendering static files like css and js.
To render them I'm commenting out app.use(express.static(__dirname + '/views')); line. This time it's rendering static files but not rendering menu_items variable in index.html .
You can see all files in this repository. Can you tell me what's I'm missing?
** UPDATE 1 **
I've added these lines instead of that commented line
app.use('/css', express.static(__dirname + '/views/css'));
app.use('/img', express.static(__dirname + '/views/img'));
app.use('/js', express.static(__dirname + '/views/js'));
But I'm not sure if it's correct way to solve my problem.
when you put the route string as `'/', the pattern matches all url requests. And the handlers registered after '/' gets ignored. So, You need to add the lines first,
app.use('/css', express.static(__dirname + '/views/css'));
app.use('/img', express.static(__dirname + '/views/img'));
app.use('/js', express.static(__dirname + '/views/js'));
and then add this router at the end,
app.get('/', function(req,res){
res.render('index', {menu_items:[{"link":"#","text":"TXT"},{"link":"#","text":"TXT"}]});
});
Related
I want to build a simple app using node.js that 'functions' like IIS/classic ASP where all the content (html, png, js, css, ejs) can be in one directory and the ejs file uses javascript vs. VBScript.
I've gathered the following from API's and other examples, but the ejs file arrives at the browser as a binary and gets saved....
My node.js file:
var express = require('express');
var app = express();
app.use(app.router);
app.use(express.static(__dirname + '/html'));
app.engine('.ejs', require('ejs').__express);
app.set('views', __dirname + '/html');
app.set('view engine', 'ejs');
app.get('*.ejs', function(req, res) {
res.render(__dirname + '/html' + req.url, function(err, result) {
res.end(result);
});
});
app.listen(8080);
My test.ejs file:
<!DOCTYPE html>
<html>
<head><title>A test</title></head>
<body>
My Test Page
<% if (1==1) { %>
Working
<%}%>
</body>
</html>
What am I missing or where can I find a working example?
I FIGURED IT OUT... SOLUTION ADDED ABOVE
express.js won't magically try to render static files, you have to explicitly call render somewhere.
I believe something like this would work:
var express = require('express')
var app = express()
app.engine('.ejs', require('ejs').__express)
app.set('views', __dirname + '/html')
app.set('view engine', 'ejs')
app.use(app.router) // only in express 3, remove that in express 4
app.get('/test.html', function(req, res, next) {
res.render('test.ejs')
})
app.use(express.static(__dirname + '/html'))
app.listen(8080)
I believe is not necessary to run render in every place, I use this example to render my static content by migrating express 2.3.7 to 4 and works fine with :
app.engine('.ejs', require('ejs').__express);
app.set('views', __dirname + '/public')
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
My static content is in 'public' directory.
I just want to add that express supports EJS out of the box these days:
https://expressjs.com/en/starter/generator.html
I have an existing coded frontend i.e views,javascripts,stylesheets (https://github.com/stdrunk/Taskr) and I intend to add this to the express framework so that i can link it to the db.
I added the contents to the public folder. The javascripts in the javascript folder, css in stylesheets, and images in images folder.
Then i changed the code of app.js according to this Render basic HTML view?
Now when run app.js and open the page in the browser i get a stripped version of my original page.
No error comes in the console.
This is my app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
//app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
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')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/home', function (req, res)
{
res.render('index.html');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
You could put all those dirs under a 'public' dir, and then use:
app.use(express.static(__dirname + '/public'));
That way, express will always just send anything requested from those directories, and you won't need to worry about static files at all.
Although, I do recommend keeping something like Apache running on your server to serve static files. Images especially.
How come the image file in my classroom.ejs is not showing if I use this
app.configure(function() {
//app.use('/room1',express.static(__dirname+'/public'));
app.use(express.static(__dirname+'/public'));
app.set('views', __dirname + '/public');
});
app.get('/room1/:nickname', function(req, res){
res.render('classroom.ejs', {title: req.params.nickname});
});
If I uncomment the app.use('/room1',express.static(__dirname+'/public'));
It works.
I need the static files to pull from /public regardless of the route and given the fact that its on top,
it should have top priority. I'm using Express 3.0.x
Can you try this:
var path = require('path');
...
app.use(app.router);
app.use('/', express.static(__dirname + '/public'));
Windows.
Node 0.8 express.js/express-resource
// Configuration of Express Application for all environments
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
//app.use(require('connect').bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public')); // for static assets (css)
app.use(express.static(__dirname + '/..')); // for static assets (css)
app.use(app.router);
});
app.resource("data", require('.....js'));
Send POST /data (in FireBug): account[foo] bar name New
in created method (req, res)
req.body is undefined.
There are some talks in the internet about a like problem (with bodyParser or Router), but I could not fix it.
A
Solved. Just in case for someone: I called app.get(..) before bodyParser middleware.
I have something along the lines of the following:
var request = require('request'),
express = require('express');
var app = express.createServer();
var port = process.env.PORT || 8080;
app.configure(function(){
app.set("view options", { layout: false, pretty: true });
app.use(express.favicon());
app.use("/public", express.static(__dirname + '/public'));
}
);
app.listen(port);
// Routes
app.get('/', function(req, resp){
resp.render('index.jade', {pageTitle: 'Some title'});
});
Yet, when I visit /public/myfile.css for example, I still get:
Cannot GET /public/myfile.css
My index.jade templates cannot seem to call the files either
Why is this?
I don't think supplying the path like that is supported:
app.use("/public", express.static(__dirname + '/public'));
Try this, and look for your public files in the root:
app.use(express.static(__dirname + '/public'));
So /public/myfile.css becomes /myfile.css.
Important also is where the position of the app.use(express.static(__dirname + '/public')) statement...
I had a problem when it was nor working when I've accidentally put this in a ./middle-conf.js file which later was imported as var configure = require('./middle-conf) and then the express app was passed into this configure(app).
So the express middle-ware processing order was not not correctly working.
this works fine...
app.use("/public", express.static(__dirname + '/public'));
and in your html pages access it like this..
<script src="/public/yourcodes.js"></script>