Express - jade cannot find views - node.js

I am currently learning Express ( + Node.js) and I am stuck with a strange error :
Error: Failed to lookup view "index" in views directory "../NODE_tests/Tutorial/app/views"
I have an index.jade in ../NODE_tests/Tutorial/app/views
doctype 5
html
body
h1 Hellow World!
and my app.js is ( should be ) correct :
// require the stuff we need
var express = require("express");
var logger = require("morgan");
var http = require('http');
// build the app
var app = express();
// Set the view directory to /views
app.set('views', __dirname + '/views');
// Let's use the Jade templating language
app.set('view engine', 'jade');
// Logging middleware
app.use(logger('combined'));
app.all('*', function (request, response, next) {
response.writeHead(200, { 'Content-Type': 'text/plain'});
next();
});
// Express routing system ...
app.get('/', function (request, response) {
response.render('index');
});
app.get('*', function (request, response) {
response.end('404 error! Page not found \n');
});
// start it up !
http.createServer(app).listen(8080, '127.0.0.1');
running node app.js is raising this error ... where am I wrong ?

for uncleared reason the index.jade file was named index.jade.log , but .log was invisible... ( copy paste from another file...)
sorry for this unnecessary question...
discover it using OSX info on the file

Related

Express not interpreting URL path correctly for static files

I am building a Node.JS app with Express and Handlebars to serve the public content. The app is running in pm2.
The app is working fine, but I want to serve static files. I added 2 static routes which are loaded fine when I check the Express log.
But when I try to access the files, I get a 404. I noticed the message on the 404 states "Cannot GET /js" where I would expect "Cannot GET /scripts/scripts.min.js".
The URL should be on /scripts/scripts.min.js, internally it's located inside a public folder:
app.js
public
scripts
scripts.min.js
images
styles
Here is my app.js:
const express = require('express');
const { engine } = require('express-handlebars');
require('dotenv').config();
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const {
NODE_ENV,
PORT,
HOST,
} = process.env;
// Use body-parser middleware
app.use(bodyParser.json());
// Use express-handlebars as the view engine
app.engine('handlebars', engine({
defaultLayout: 'main',
layoutsDir: __dirname + '/views/layouts',
partialsDir: __dirname + '/views/partials',
}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')))
app.use('/scripts/monaco/', express.static(path.join(__dirname, 'node_modules','monaco-editor','min','vs')));
// Define routes
app.get('/', (req, res) => {
res.render('home', { title: 'Home' });
});
app.get('/debug', (req, res) => {
res.send(__dirname + '/public')
})
app.post('/', (req, res) => {
console.log(req.body);
res.send('Success');
});
// Load external routes (also tried the staticFiles by using res.sendFile)
require('./routes/processing')(app);
// require('./routes/staticFiles')(app);
// Start the server
app.listen(PORT, () => {
app.currentServer = {
host: HOST ? HOST : "127.0.0.1",
port: PORT,
};
console.log(`Server init on: http://:${PORT}`);
});
I tried serving the files using express.static, I also tried sending them trough specific routes by using res.sendFile.
It looks like Express (or something else) is interpreting the URL path incorrectly. /scripts/scripts.min.js is downgraded to /js so it seems.
I hope anybody has a clue!

Node.js Express not rendering html view

so I was trying to follow a tutorial to use node.js as the front end of a wordpress site
This one http://www.1001.io/improve-wordpress-with-nodejs/
Here is the code from server.js
var frnt = require('frnt');
var fs = require("fs");
var path = require("path");
var express = require('express');
var app = express();
var doT = require('express-dot');
// Define where the public files are, in this example ./public
app.use(express.static(path.join(__dirname, 'public')));
// Make sure this is set before the frnt middleware, otherwise you won't
// be able to create custom routes.
app.use(app.router);
// Setup the frnt middleware with the link to the internal server
app.use(frnt.init({
proxyUrl: "http://localhost:8888/frnt-example/wordpress", // The link to your wordpress site
layout: false // We simplify this example by not using layouts
}));
// define rendering engine
app.set('views', path.join(__dirname, "views"));
app.set('view engine', 'html' );
app.engine('html', doT.__express );
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('./views/index.html');
});
app.listen(8080); // listen to port 8080
It keeps outputting the following
./views/index.html
Rather than rendering the html?
I've never used frnt, but res.send sends a string so that's no big surprise.
Look at res.sendfile which sends the contents of a file.
I prefer to use ejs , it's sems like html just edit index.html to index.ejs
1- install ejs module npm install ejs
2- add this in app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
and render the index.ejs by using
app.get('/', function (req, res) {
res.render('index'); // or res.render('index.ejs');
});
res.send() // it send just a string not file
Hope it usefull !

Failed to lookup view

Hi I'm trying to work with Express 3 using handlebars. But I am unable to "lookup the view" I am stuck with this error.
Error: Failed to lookup view "500" in views directory
"d:\projects\meadowlark\site\views" at EventEmitter.app.render
(d:\projects\meadowlark\site\node_modules\express\lib\application.js:519:17)
at ServerResponse.res.render
(d:\projects\meadowlark\site\node_modules\express\lib\response.js:904:7)
at d:\projects\meadowlark\site\meadowlark.js:29:7 at
Layer.handle_error
(d:\projects\meadowlark\site\node_modules\express\lib\router\layer.js:58:5)
at trim_prefix
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:269:13)
at
d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:238:9
at Function.proto.process_params
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:313:12)
at
d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:229:12
at Function.match_layer
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:296:3)
at next
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:190:10)
Its really strange for me. Can anyone explain this issue to me how can I solve it?
My js code is as follows:
var express = require('express');
var app = express();
// set up handlebars view engine
var handlebars = require('express3-handlebars')
.create({ defaultLayout:'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port',process.env.port || 3000);
app.get('/', function(req, res) {
res.render('home');
});
app.get('/about', function(req, res) {
res.render('about');
});
// 404 catch-all handler (middleware)
app.use(function(req, res, next){
res.status(404);
res.render('404');
});
// 500 error handler (middleware)
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'),function(){
console.log('Express started on http://localhost: '+ app.get('port') + " Press CTRL+C to terminate.");
});
I think I know what the issue here is, remember this setup of app.js from an O'Reilly book ("Web Development with Node & Express").
Here's what the author fails to clarify:
If you have your .handlebars template files in views/layouts/, structure your view engine setup like this:
var path = require('path');
var express = require('express');
var handlebars = require('express-handlebars'); // 'express3-handlebars' has been deprecated
var app = express();
// Set up handlebars view engine
app.set('views', path.join(__dirname, 'views/layouts/'));
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
Note that you will need the var path = require('path'); in order to set 'views' to the filepath views/layouts/.
If you read the error, it clearly tells you that you are missing a 500 view template in your template directory. I'm not sure what your directory structure you have, but place a 500.handlebars file in the same directory the 404.handlebars file is. Should be somewhere in the views/ or views/layouts directory.
Make sure that your files: home.handlebars, about.handlebars, 404.handlebars, 500.handlebars and main.handlebars don't have hidden extensions. Like this: home.handlebars.html, about.handlebars.html, 404.handlebars.html, 500.handlebars.html, and main.handlebars.html.
If they do, removing those extensions and using only the .handlebars extension should resolve the issue.

Node.js sending html file doesn't load linked files (css, js)

I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);

express 3.0 bodyParser not working properly

I am using latest version of express no.3 . I have read the docs and did exactly as was written but it is still not working as it suppose to .I get file in my upload dir after submit but then everything stops and callback function from app.post doesn't fire . The code:
HTML-JADE
form(action="/upload", method="post", enctype="multipart/form-data")
input(type="file", name="image")
input(type='submit', value='submit')
App.js
var express = require('express')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, mongo = require('mongodb')
, Server = mongo.Server
, Db = mongo.Db
, routes = require('./routes')
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir:'./upload'}));
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.post('/upload', function(req, res) {
console.log(req.files.image) // this doesn't fire at all - no matter what i write here
res.send(200) //doesn't run also
});
You need to return a response after reading the data. Without returning a response, express has no idea of when your response is finished and node will not close the connection to the client.
try this:
app.post('/upload', function(req, res) {
console.log(req.files.image);
req.on('data', function(raw) {
console.log('received data');
});
req.on('end', function() {
console.log('end');
res.send(200);
});
}
Try sending a simple response to the user.
app.post('/upload', function(req, res) {
console.log(req.files.image);
res.write('File Uploaded !!');
res.end();
}
Update
You should try changing the format to
app.post('/upload', function(err,req,res,next){
//Check for errors then handle it
}
Can't tell much until I know what errors you are getting, since file is being uploaded to upload dir bodyParser is working fine. Maybe your route is being handled by another function, or not handled at all. app.router is code that calls the callback .
When you do app.get('/upload', function(req, res) { ... }); it is the router that actually invokes the callback function to process the request. Can you confirm if you can do app.get('/upload',...); the html-jade file succesfully. If not then there is a problem in your routes.
Finally I found solution - that was because i used node 0.9.6 -pre. After change to 0.8.21 everything works fine.
Thanks all for your help.

Resources