Root not working for admin pannel in node js - javascript

I am tring to give 2 roots one for admin and other for user.
To access the admin pannel http://localhost:3000/admin
To access to user page http://localhost:3000.
But the problem is when an option is selected from the menu of admin pannel it will not take to that page , and shows a 404 error.[if i click option which have an href add-faq it must show like http://localhost:3000/admin/add-faq. but it is showing http://localhost:3000/add-faq and giving 404 error]
But the user page had no problems.
I am using node js,Express,Hbs.
All files are named properly and no files missing..
If the http://localhost:3000/admin/add-faq is manually given the stylesheets are not loading (404)
GITHUB :https://github.com/bimalboby/clevercode
PLEASE HELP AND THANKS IN ADVANCE😊
My App.js file:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
var hbs = require('express-handlebars')
var app = express();
var db=require('./config/connection')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs',hbs({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts',partialsDir:__dirname+'/views/partials'}))
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')));
db.connect((err)=>{
if(err) console.log('connection failed'+err);
else console.log('connected to database');
})
app.use('/', userRouter);
app.use('/admin',adminRouter);
// 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;```
**My admin.js:**
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('adminintro',{admin:true})
});
router.get('/add-prices', (req,res)=>{
res.render('faqadmin',{admin:true})
});
router.get('/add-faq',(req,res)=>{
res.render('faqadmin',{admin:true})
})
module.exports = router;
**my user.js:**
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index',{admin:false,indexpage:true});
});
router.get('/faq',(req,res)=>{
res.render('faq',{indexpage:true})
});
router.get('/web-design-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
router.get('/e-commerce-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
router.get('/seo-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
module.exports = router;

Try adding the complete end point like below in /views/partials/admin-header.hbs file like below,
<li>FAQ</li>
Your user routes are with the endpoint '/' in server.js.So its working,where as admin need to be linked like /admin/add-faq

Related

All routes except the index route showing an Error 404 while developing on the Express Application Generator

I am building a day planner, and while I was setting the routes I noticed I am receiving a 404 for every routes other than the main Home page route ie, index or "/".
This is app.js file
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var calendarRouter = require('./routes/calendar');
var app = express();
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb+srv://<user-name>:<password>#cluster0.3xw67.gcp.mongodb.net/<db-name>?retryWrites=true&w=majority';
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/', indexRouter);
app.use('/users', usersRouter);
app.use('/calendar', calendarRouter);
// 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;
This is the calendar.js route
var express = require('express');
var router = express.Router();
var schedule_controller = require('../controllers/scheduleController');
router.get('/', schedule_controller.index);
router.get('/calendar/create', schedule_controller.schedule_create_get);
router.post('/calendar/create', schedule_controller.schedule_create_post);
router.get('/calendar/:id/delete', schedule_controller.schedule_delete_get);
router.post('/calendar/:id/delete', schedule_controller.schedule_delete_post);
router.get('/calendar/:id/update', schedule_controller.schedule_update_get);
router.post('/calendar/:id/update', schedule_controller.schedule_update_post);
router.get('/calendar/event/:id', schedule_controller.schedule_details);
router.get('/events', schedule_controller.schedule_list);
module.exports = router;
This is the index.js route, I did a redirect here!
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.redirect('/calendar');
});
module.exports = router;
And here is the Controller for the calendar.js route.
var Schedule = require('../models/schedule');
exports.index = function(req, res) {
res.send('NOT IMPLEMENTED: Site Home Page');
};
exports.schedule_list = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule List');
};
exports.schedule_details = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule Detail: ' + req.params.id);
};
exports.schedule_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create GET');
};
exports.schedule_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create POST');
};
exports.schedule_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete GET');
};
exports.schedule_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete POST');
};
exports.schedule_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update GET');
};
exports.schedule_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update POST');
};
Okay I found the bug it was me using index url that is / which I redirected to /calendar. And I have been using the rest of the url routes without calling the redirected one ie, /calendar.
I tried calling the routes with /calendar/calendar and it works!
I don't yet know clearly how to explain this. I hope fellow stackoverflow'ers could explain why this is happening.
Here's me trying a noob explanation!
Redirecting index route / to another url route, changes the main url route of the website(address). So all the sub routes which is everything other than the index route should explicitly call the redirected route (new address). Because every-time we call the old address the redirection changes it to the new one. Making the old address a dead one.
(Humour : I would like to point out an example considering numbers. It's like whole numbers and natural numbers. Redirection is when the whole number changes to natural number.)

req.body throws an empty {}

I am using body-parser but it's not working and I don't know what the problem is.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
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('/', indexRouter);
app.use('/users', usersRouter);
// 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;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', redirection, function(req, res, next) {
res.redirect('index', {title: 'Home'});
});
router.get('/country', function(req, res, next) {
// CountryName
res.render('country',
{
title: 'Home',
mainJS: 'main.js',
//country: req.body.countries
});
console.log(req.body)
});
function redirection(req, res){
if (req.url == '/'){
res.redirect('/country');
}
}
module.exports = router;
In this code it throws {}
What is the problem?
Your server only receives a request body in POST (or PUT or PATCH) operations, not in GET operations. You don't have router.post() in your sample code, so it seems you are not handling POSTs. Therefore, no req.body.
You can find your https://example.com/?query=parameters&query2=parameters at req.params.query and req.params.query2.
You can't use the location bar of a browser to do a POST: they from a form posts or xhr / fetch operations.

I am getting an error "indexRouter is not defined"

I am getting an error "indexRouter is not defined while I am trying to execute the following code. I tried removing the line but again there are other errors. Can anyone tell me why we are using this common variable router for both index.js and user.js?
This is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');
const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url,{
useMongoClient : true
});
connect.then((db) => {
console.log('Connected correctly to the server');
},(err) => {console.log(err);});
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('/index',indexRouter);
app.use('/users',usersRouter);
// 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;
This is my index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
This is my users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
You are using wrong variable.
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/index',indexRouter); // it would be index
app.use('/users',usersRouter); // it would be users
Change from indexRouter to index and userRouter to users.

Node sub-route returning 404

I have just started using node.js with the Express framework, and I am trying to understand how the built in routing works. I have found that a "main" router can be defined from which other "sub-routes" are used. For now, my app initially makes a get request that loads a dropdown from a MySQL database. I added a demo button that should take the value in the dropdown and make a request with it as a query parameter to my sub-route. When the button is clicked for the sub-route, I am getting a 404. 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 routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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;
My index.js (main route):
var express = require('express');
var router = express.Router();
var models = require('../models');
router.use('/savings', require('./savings.js'));
/* GET home page with locations and their initial data collection dates */
router.get('/', function(req, res, next) {
models.Location.findAll({
attributes: ['locationName', 'initializationDate']
}).then(function(locations) {
res.render('index', {
title: 'Solar Data Savings',
locations: locations
});
});
});
module.exports = router;
savings.js (sub-route):
var express = require('express');
var router = express.Router();
var models = require('../models');
/* GET calculate solar data savings and reroute */
router.get('/savings', function(req, res, next) {
req.param('locationID');
models.Bank.findAll({
attributes: ['bankID'],
include: [{
model: Location,
where: { locationID: Sequelize.col('bank.locationID') }
}]
}).then(function(banks) {
res.render('index', {
title: 'Solar Data Savings',
banks: banks
});
});
});
module.exports = router;
index.pug:
extends layout
block content
div(class="container-fluid")
h1= title
p This is the #{title} project website
form(action="/savings")
div(class="form-group")
label(for="locations")
div(class="col-sm-4")
select(id="locations" class="form-control")
-for(var i = 0; i < locations.length; i++) {
option(value="#{locations[i].dataValues.locationID") #{locations[i].getLocationName()}
-}
div(class="col-sm-4")
input(type="submit", value="Get Bank")
I believe I am misunderstanding a nuance to routing, and I've scoured the web for a solution to this particular problem with no luck. Help greatly appreciated
Your savings route on the server is set to /savings/savings whereas your form is calling /savings. Either change the form or change the server side:
In savings.js, change
router.get('/savings', function(req....
to
router.get('/', function(req....
Also, you are using get to submit a form. Maybe you need to change that to
router.post('/', function(req...
Just make following changes in index.pug :
extends layout
block content
div(class="container-fluid")
h1= title
p This is the #{title} project website
form(action="/savings/savings")
div(class="form-group")
label(for="locations")
div(class="col-sm-4")
select(id="locations" class="form-control")
-for(var i = 0; i < locations.length; i++) {
option(value="#{locations[i].dataValues.locationID") #{locations[i].getLocationName()}
-}
div(class="col-sm-4")
input(type="submit", value="Get Bank")
Actually your routing is wrong:
Currently you're calling as : your_url:port/savings
BUT Should be : your_url:port/savings/savings
LINE NEEDS CORRECTION
FROM : form(action="/savings")
TO : form(action="/savings/savings")

How to properly apply routes inside another file

I'm fairly new to express js and I want to know how to use router. I created a file named categories.js inside routes directory with this code.
categories.js code:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/categories', function(req, res) {
res.send('this is the category');
});
module.exports = router;
inside the app.js i have this 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 users = require('./routes/users');
var categories = require('./routes/categories');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// 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('/categories', categories);
// 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;
I have tried understand what is wrong but i can't see to figure out. thanks in advance.
This is the error im getting
Not Found
404
I will like to add inside the routes directory i have a index.js file and this one works.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
I think my application is not reading the categories.js file, because when I put the category.js code inside index.js it works. but it doesn't work if i put it in a separate file in my case category.js.
I think you've got your categories route hooked up wrong, your categories are mapped to /categories/categories in your code. To fix it, try this in your app.js:
app.use('/', categories);
If you don't want to prefix, you can also simply do this:
app.use(categories);

Categories