external css files break jade view - javascript

Am new to node.js and am sorry if the answer to this question is too obvious
i build my app logic with all the routes and views and it work all fine , till i wanted to extend more styles to my views which i used Jade to build them as am using Express, the only change i did is i included bootstrap to my layout.jade
link(rel="stylesheet", href="bootstrap.min.css")
and my app break with 500 error.
note the bootstrap.min.css located in the public folder, also i noticed that in the console i got the right response before the error.
here is the error i got :
Error: Failed to lookup view "error" in views directory
"C:\Users\myuser\Desktop\mySpace\myApp\views"at Function.app.render
(C:\Users\myuser\Desktop\mySpace\myApp\node_modules\express\lib\application.js:493:17)
app.js
/*
* # db the string to connect the database as its used in mongoose_connection to store sessions.
*
*/
module.exports = function(items, db){
var express = require('express');
// Include the module to enable session using connect-mongo
var mongoStore = require('connect-mongo')(express);
// Include the module auth that using passpord module to authnticate user.
var passport = require('./auth');
// Include stylus module.
var stylus = require('stylus');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes')(items);
var app = express();
// Compile function for stylus.
function compile(str, path) {
return stylus(str).set('filename', path);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
//Middleware to store sessions
app.use(express.session({
secret : 'keyboard cat',
store : new mongoStore({
mongoose_connection : db
})
}));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
// using passport as application midleware.
app.use(passport.initialize());
// telling session to use session in express.
app.use(passport.session());
//stylus middleware
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static(path.join(__dirname, 'public')));
/*
*Middleware to modifiy the header.
*/
app.use(function(req,res,next){
res.set ('X-Powered-By' , 'Myapp');
next();
});
app.use(app.router);
app.put('/app/setItem/:id', routes.setItem);
app.get('/app/findAllItem', routes.findAllitem);
app.get('/app/findById/:id',routes.findById);
app.get('/app/getJitems',routes.getJitems);
/*
*The routes of the login process 3 routes
*# the login form
*# the login post information and checking
*# the success redirect route
*/
// login form route
app.get('/login', routes.login);
// check user route
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/user'
}));
//success login route
app.get('/user', routes.user);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
return app;
}

That's because it can't find "bootstrap.min.css", your 404 handler throws an error rather than generating a response, and you have no template for rendering error responses.
There are three problems you need to fix here:
Assuming bootstrap.min.css is in the root "public" directory and is meant to be used site-wide, it should be linked with the absolute path "/bootstrap.min.css", like so:
link(rel="stylesheet", href="/bootstrap.min.css")
Note the leading slash. Without the slash, a path like "bootstrap.min.css" is interpreted as a sibling of the current location, meaning that its inclusion on a page like "/users/500/example" would lead the browser to look for it at "/users/500/bootstrap.min.css".
Your "404 handler" should actually send a response, rather than throwing an error.
You should either:
create an error template,
replace the res.render call in the error handler with res.send,
or delete the error handler altogether and fall back to Express's default error handler.

Related

Node JS - "Could not get any response" On Insert Data to Database

I'm trying to Insert some data to my database(mysql) with nodejs and I already did make some code but in postman it displays Could not get any response even though I know that I followed properly some tutorials that I watched.
Here's my code
SendOrder.js (models)
var db=require('../dbconnection');
var Task = {
addTask:function(Task,callback){
return db.query("Insert into orders ( order_id, order_no, tbl_id, menu_id, \
order_quantity, order_discount, order_type, \
order_amount, menu_name, menu_price ) values(?,?,?,?,?,?,?,?,?,?)",
[
Task.order_id, Task.order_no, Task.tbl_id, Task.menu_id,
Task.order_quantity, Task.order_discount, Task.order_type,
Task.order_amount, Task.menu_name, Task.menu_price
], callback);
},
}
module.exports=Task;
SendOrder.js (router)
var express = require('express');
var router = express.Router();
var Task = require('../models/SendOrder');
router.post('Send/', function(req, res, next){
Task.addTask(req.body,function(err,count){
console.log(req.body);
if(err)
{
res.json(err);
}
else{
res.json(req.body);
}
});
});
module.exports = router;
EDIT:
dbconnection.js
var mysql=require('mysql');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'opob',
});
module.exports=connection;
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var connection = require('express-myconnection')
var SendOrder = require('./routes/SendOrder'); // SendOrder
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/SendOrder', SendOrder); // SendOrder
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Go to Setting in Postman
Off the SSL certificate verification in General tab: (Second option under Request)
Off the Global Proxy Configuration and Use System Proxy in Proxy tab:
If both not work, try below code:
if(err)
{
return res.status(500).json(err);
}
else{
return res.status(200).json(req.body);
}
Hope, this may help you!
=========== EDITED ==============
Looking at your app.js file. It seems you need to use body-parser package to parse the JSON data from request.
npm install body-parser --save
body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.
From whatever you have shared here are the following possibilities:
Your IP/PORT that you are trying to hit is wrong. Please cross verify them again.
The IP that you are trying to hit is not accessible from the machine where postman is installed (I added this possibility as you are using IP instead of localhost)
The third possibility would be server crashing when you hit the Send/ API. If the problem is with your code, most probably this is the reason. In this case, you can check the server console to find crash logs and stack-trace.
As #Hardik has mentioned in the comments is not a wrong URL as that would return 404.

Keep on getting the following warning on my node.js server

My console keeps on giving the following warnings. This could be from app.js or from any of the other route files:
The error seems to be coming because of my cache handling. I handle cache once the user logs out.
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/response.js:163:12)
at done (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/response.js:957:10)
at View.exports.renderFile [as engine] (/home/ved/Dropbox/JAVA/eBay/test/node_modules/ejs/lib/ejs.js:363:10)
at View.render (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/view.js:126:8)
at tryRender (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/application.js:639:10)
at EventEmitter.render (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/application.js:591:3)
at ServerResponse.render (/home/ved/Dropbox/JAVA/eBay/test/node_modules/express/lib/response.js:961:7)
at /home/ved/Dropbox/JAVA/eBay/test/app.js:159:7
GET /fonts/glyphicons-halflings-regular.woff 404 1.673 ms - 968
GET /fonts/glyphicons-halflings-regular.ttf 404 1.738 ms - 968
POST /viewProductPage - - ms - -
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//DEFINING EXTERNAL DEPENDENCY TO ENABLE SESSIONS IN THE APPLICATION
var session = require('client-sessions');
//DEFINING THE BASE ROUTE
var routes = require('./routes/index');
//DEFINING THE ROUTE TO GET THE SYSTEM USERS
var users = require('./routes/users');
//DEFINING THE ROUTE TO ACCESS sell.js
//sell.js HANDLES ALL THE ITEMS POSTED
//INTERACTS WITH THE DATABASE FOR THE SAME
var sell = require('./routes/sell');
//ROUTES TO getUserData.js
//DEFINED AS A BASE ROUTE TO ACCESS SESSION FOR ANY USE
var getUserData = require('./routes/getUserData');
var productsRetriever = require('./routes/productsRetriever');
//DEFINING THE DEPENDENCY TO ACCESS LOGIN CONTROLS FOR THE SYSTEM
//USER LOGIN AND MOST IMPORTANTLY ASSIGNING A SESSION TO THAT USER IS HANDLED BY login.js
//getUserData.js RETRIEVES THE SESSION OF A USER INITIATED IN login.js
var login = require('./routes/login');
var productDetail = require('./routes/productDetail');
//DEFINING THE DEPENDENCY TO ACCESS register.js
//register.js HANDLES ALL THE USER REGISTRATION PATHS AS WELL AS FUNCTIONS
var register = require('./routes/register');
//INITIATING AN INSTANCE OF express js IN OUR APPLICATION
//ASSIGNING IT TO A VARIABLE APP
var app = express();
// all environments
//configure the sessions with our application
app.use(session({
cookieName : 'session',
secret : 'cmpe273_ebay_app_fall_2016',
duration : 30 * 60 * 1000, //setting the time for active session
activeDuration: 5 * 60 * 1000 // setting time for the session to be active when the window is open // 5 minutes set currently
}));
// view engine setup
//SETS BASE PATH FOR ALL THE FILES IN THE VIEW
app.set('views', path.join(__dirname, 'views'));
//ASSIGNING THE ejs ENGINE TO ALL THE FILES WITHIN VIEWS DIRECTORY
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//GETS THE PATH WHEN A USER FIRST VISITS OUR APPLICATION
app.get('/', routes);
app.get('/users', users);
app.get('/login', login.login);
app.post('/checklogin', login.checklogin);
app.get('/getAllUsers', login.getAllUsers);
app.get('/sell', sell.sell);
app.post('/addSellItem', sell.addSellItem);
//app.post('/checklogin', login.checklogin);
app.get('/homepage',login.redirectToHomepage);
app.post('/logout',login.logout);
app.post('/getUserInfo', getUserData.getUserData);
app.get('/viewProduct',productDetail.getProductPage);
app.post('/productsRetriever', productsRetriever.getProducts);
app.post('/viewProductPage', productDetail.getProductPageDetails);
app.get('/register', register.register);
app.post('/registerdone', register.registerdone);
app.get('/getAllRegisteredUsers', register.getAllRegisteredUsers);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message : err.message,
error : err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message : err.message,
error : {}
});
});
module.exports = app;
This has happened to me also.
What the issue was (for me) was that I was doing some operations in my routes and was sending response to user but after that error occured and it was handled by the error handling middleware (bottom part of your app.js) and it was sending the error response.
But as the request was already responded to earlier in your API route, this error message comes in the logs. Try finding what the error is.
Try putting console.log() in your error handlers to see the trace.

Node Express Routing Problems

I´m currently trying to render my .ejs-templates with some variables, but I´m kinda stuck and can`t help myself. I´ve installed express over the express-generator with compass and ejs.
In my routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.write('Hello World')
res.end();
});
module.exports = router;
So I want to render <%= name %> in index.ejs (views/index.ejs) with the name Jack. In a few tutorials it should work this way, but it just don`t works for me.
I got an error telling me that the variable name is not defined. Would be very nice, if you guys could tell me, what I´m doing wrong or what I´ve missed.
I´m using ejs the first time and just can`t figure out my mistake =/
This is my app.js server-file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require("http");
var routes = 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');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('node-compass')({mode: 'expanded'}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
regards,
Cab
edit: I figured out that the rendering of the variable title works, but all the other variables don`t work. I can imagine, that I can only access some kind of global variables and title is one of them =/
edit2: Found out, that my routing isnt working properly ... so the rendering isnt working ofc. But can`t figure out my mistake =/
If you have split your project up into different modules then you need to export those modules so they are available in other parts of your app.
For example you have separate route modules where you are defining your routes. For these to be available to the rest of your app then you need to make them available using the module.exports command.
so at the end of routes/index.js you need to have
module.exports = router;
The end of the express page on routing gives an example

file upload in express js giving problems again

Though I have read quite a few questions being answered on stackoverflow, I'm still unable to get it to work even after a couple of days of trying. It's my first week with express and node and so I don't know if I'm doing the small things right. I basically want to upload a file and later on save it to the file system, however, I'm unable to proceed with req.files giving me undefined. Please see my code below.
This is my app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var routes = require('./routes/index');
var users = require('./routes/users');
var upload = require('./routes/upload.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/upload', upload);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
This is my routes/upload.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
console.log("");
console.log(req.files);
res.send('this is the page you get upon doing file upload');
});
module.exports = router;
This is my views/homepage.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
p select file to upload
form(action="upload", method="get", enctype="multipart/form-data")
input(type="file", name="displayImage")
input(type="submit")
At the moment, I'm hearing a lot of terms like multer, connect-busboy, bodyParser being deprecated from express4 etc but with no real idea on how to proceed. Please advise me on how I can proceed and what code should be added.
Thanks.
You need a middleware module that can parse your uploaded file.
Like such:
https://github.com/expressjs/multer
https://github.com/mscdex/connect-busboy
Then use the middleware in your index.js, like:
app.use(multer({ dest: './uploads/'}))
or
app.use(busboy());
A number of modules were removed from Express in 4.0 and are now separate packages you have to include. The easiest way to get started with it is to use express-generator to generate the scaffolding for you. This will include and require the correct packages for parsing cookies, and the request body. It doesn't include a file parser however. I put together an example using multer and put it on Github for you to reference.
After you clone it, you can run npm install, and then npm start.
One other thing you were doing incorrectly that I fixed was using app.get for your upload handler. You can't use GET to upload a file. In my example I changed this to a POST request. Here are the relevant snippets.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var routes = require('./routes/index');
var users = require('./routes/users');
var upload = require('./routes/upload');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(multer({ dest: './uploads/'}))
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/upload', upload);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.jade
extends layout
block content
h1= title
p select file to upload
form(action='upload', method='post', enctype='multipart/form-data')
input(type='file', name='displayImage')
input(type='submit')

Node.js public css files 404 not found

I'm learning node.js and I have an error serving public CSS files to one URL.
It works with almost every pages, I go on the page and the css file is loaded from 127.0.0.1/css/style.css.
When the URL is 127.0.0.1/project/idProject it tries to get the css file from 127.0.0.1/project/css/style.css.
// INCLUDE MODULES =======================================================
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(express.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash())
// ROUTES =======================================================
// Set authentication variable
app.use(function (req, res, next) {
app.locals.login = req.isAuthenticated();
next();
});
require('./app/routes.js')(app, passport);
//ERROR MANAGEMENT =======================================================
app.use(app.router);
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('errors/404.twig', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
/*app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('errors/500.twig', { error: err });
});*/
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
console.log("New connection");
});
// LISTEN SERVER =======================================================
server.listen(80);
Any idea on how to solve this ?
Regards !
I tried approach which I saw in the comments, and because it did not work for me, I am posting an answer that worked.
All .css files are static, so you have to serve them to the client. However, you do not serve static files as a express middleware. Therefor you have to add them.
app.use(express.static(__dirname, 'css'));
Hi it was a problem for me to solve this, but with the help of salvador it was posible.
The only thing that im going to put is all the code and the you make the reference in the html, you only need to put the file not the folder in the html file.
//The index.js code
var express = require('express');
const path = require ('path');
//app va a ser mi servidor.
var app = express();
app.set('port', 3000)
//app.use(express.static('./public'));
//app.use(express.static( 'css'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'css')));
app.listen(app.get('port'), () => {
console.log('localhost:3000')
} );
this is the structure

Categories

Resources