Routes not redirecting to static file - javascript

I want to serve index.html in docs/ subdirectory of public folder as static file. The index file should be served both at /index.html and / URLs.
Below is my app.js code
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 routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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')));
app.use('/', routes);
// 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;
Below is my routes.index code
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log("comes in");
//res.sendFile(path.join(__dirname, 'public/', 'docs/index.html'));
//res.sendFile('index.html', { root: path.join(__dirname, './public') });
res.sendFile('/docs/index.html');
});
When i run localhost:3000, it does not re-direct to /docs/index.html [static content]

Please try below code:
res.sendFile(__dirname + '/doc/index.html');

Related

"req.getConnection is not a function" Node.js

Im having trouble connecting Node.js application with sql database.
Error occurs is "req.getConnection is not a function".
I am trying to get data from the database the moment I click on a certain page (eg.users).
My code is as below
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 flash = require('express-flash');
var session = require('express-session');
var expressValidator = require('express-validator');
var methodOverride = require('method-override');
var connection = require('express-myconnection');
var mysql = require('mysql');
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', 'jade');
// 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(session({secret:"mysecretpass"}));
app.use(flash());
app.use(expressValidator());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body)
{
var method = req.body._method;
delete req.body._method;
return method;
}
}));
/*-----------------------------------------
* Connection peer, register as middleware
* type koneksi:single,pool and request
-----------------------------------------*/
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
// 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;
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('dashboard', { title: 'Dashboard' });
});
router.get('/admin_users', function(req, res, next) {
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM users',function(err,rows)
{
if(err)
var errornya = ("Error Selecting : %s ",err );
req.flash('msg_error', errornya);
res.render('admin_users',{title:"Admin Users",data:rows});
});
//console.log(query.sql);
});
});
module.exports = router;
You are adding the express-myconnection middleware after your routes middleware. Middleware is executed in the order it is added, and as such the getConnection function is not defined on the req object until after your express-myconnection middleware is executed.
Simply move the connection middleware above the usage of routes, ie.
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
app.use('/', routes);
app.use('/users', users);

External CSS in Node JS

I am trying to bind my style into some external CSS that I have in my project directory.
My app structre looks like this:
webDTU
app.js
public/
stylesheets/
style.css
avgrund.css
animate.css
views/
index.jade
UserHome.jade
....
....
my UserHome.jade:
doctype html
html
head
title MQTT Chat Application
script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js')
link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic', type='text/css')
link(rel='stylesheet', href='../public/stylesheets/animate.css', type='text/css')
link(rel='stylesheet', href='../public/stylesheets/style.css', type='text/css')
link(rel='stylesheet', href='../public/stylesheets/avgrund.css', type='text/css')
body
.avgrund-contents
header
h1 hi #{title}
.pr.center.wrapper
.cf.pr.chat.animate
.pa.chat-shadow
.....
my 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 mongoose = require('mongoose');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/webDTU');
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', 'jade');
// 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')));
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
// 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;
My problem is that somehow href='../public/stylesheets/animate.css' does not load the correct file from my project directory and I do not understand why it does not work.
Then in html use
href='/public/stylesheets/animate.css'

In Webstorm node express app: router.post() shows error: unresolved function or method post()

When I run the localhost:3000/users/yu , I get a 404 not found. Why is the post() coming up as undefined? when I run a POST from my iOS app I get a "undefined token" error. I'm running node v5.7.0 and express v4.13.4 Project was generated using express-generator to create Webstorm project.
var express = require('express');
var router = express.Router();
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res) {
res.send("yoma");
});
router.post('/yu', function(req, res) {
var test = req.body;
//parse test
});
My app.js looks like this:
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 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
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;
when you navigate your browser to localhost:3000/users/yu it makes GET http query, but in your router you have only POST handler for '/yu'
router.post('/yu', function(req, res) {
console.log(req.body);
});
Add GET handler for '/yu' like this for example
router.get('/yu', function(req, res) {
console.log(req.body);
});
After that you should not get a 404 error when navigate to localhost:3000/users/yu

Express routers aren't working

I'm starting to learn Node and Express, but I currently can't get some of my routes to work.. Here's the app.js file that I'm currently using
EDIT: Here's my updated files, but I stil get a 404
var db = require('./db');
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 session = require('express-session');
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', 'jade');
// 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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
//res.send(req.path)
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;
And the route I can't view is '/users/userlist' here is my userlist.js route
EDIT: I've moved '/users/userlist' into the users.js route
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
var params = req.params[0].split("/");
if(params.length>=2){
var newUser = new User({username: params[0], password:params[1]});
newUser.save(function(err, fluffy){
if(err)
res.send(err);
});
}
res.send('Account Created!');
});
router.get('/users/userlist', function(req, res) {
var users;
User.find(function(err, _users){
if(err)
users="ERROR";
else
users=_users;
});
res.send(users);
});
module.exports = router;
When I try and point my browser to http://localhost:3000/users/userlist I just get a 404.
You have made a mistake while declaring routes in app.js,remove below code.
app.use('/users/userlist',userlist);

404 Error in Node Application

Not Found
404
Error: Not Found
at c:\Users\wf\WebstormProjects\nodeExpress\app.js:33:13
at Layer.handle [as handle_request] (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:312:13)
at c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:280:7
at Function.process_params (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:330:12)
at next (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:271:10)
at c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:618:15
at next (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:256:14)
at Function.handle (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:176:3)
at router (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:46:12)
router code:
//about.js
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res, next) {
console.log("/about route");
res.render('about', { title:'About',name:'Praveen' });
});
module.exports = router;
//app.js code
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 routes = require('./routes/index');
var about = require('./routes/about');
//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(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')));
app.use('/', routes);
app.use('/about', about);
//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;
enter code here
I'm getting above error if I try to access different route in my node application. Please help
The issue here is that the route in the about file is actually being resolved as /about/about. If you try open that URL it should work fine.
This is because in app.js, you say 'forward all requests that start with /about to about.js', so in about.js all routes already start with /about: app.use('/about', about);
To fix this, simply update the route in about.js to:
router.get('/', function(req, res, next) {

Categories

Resources