middleware is not working in nodejs - node.js

I have this code:
exports.get_transducer_edit = (req, res) => {
if(req.isAuthenticated()){
Transducer.findById(req.params.id, (err, foundTransducer) => {
if(err){
res.redirect('/en/dashboard');
} else {
res.render('dashboard/transducer_edit-dashboard', {transducer: foundTransducer});
}
});
}else{
req.flash('error','You need to log in to do that');
res.redirect('/dashboard/login');
}
};
it runs with no problem, but then when I created a middleware in middleware/index.js:
var middlewareObj = {};
middlewareObj.isLoggedIn = function(req, res, next){
if(req.isAuthenticated() ) {
return next();
}
res.redirect('/dashboard/login');
};
module.exports = middlewareObj;
I called it inside this code:
const middleware = require('../middleware');
const Transducer = require('../models/productTransducers');
exports.get_transducer_edit = middleware.isLoggedIn, (req, res) => {
Transducer.findById(req.params.id, (err, foundTransducer) => {
if(err){
res.redirect('/en/dashboard');
} else {
res.render('dashboard/transducer_edit-dashboard', {transducer: foundTransducer});
}
});
};
What am I doing wrong? Please help...

Sorry, I just solved.
I called the middleware in my route:
router.get('/en/dashboard/products/transducers/:id/edit', middleware.isLoggedIn, transducer_controller.get_transducer_edit);
I was trying to call it in my controller like:
exports.get_transducer_edit = middleware.isLoggedIn, (req, res) => {
...
wrong!
Thanks again.

Related

passing data to partial express js hbs

currently I am making a notification system with node/express/hbs and mysql. I can insert notification to the database properly , but I can't fetch it my partial file.
here is my code
countNotification: async (req, res) => {
await Notification.count({ where: { status: 'unread' } }).then((notification) => {
if (notification) {
const dashNotification = req.notification;
return dashNotification;
}
});
},
app.use((req, res, next) => {
res.locals.user = req.user;
res.locals.notification = req.dashNotification;
next();
});
i have tried this like that but it is not working , anyone has any solution ?
You should use your middleware above the router:
app.use((req, res, next) => {
res.locals.user = req.user;
res.locals.notification = req.dashNotification;
next();
});
countNotification: async (req, res) => {
await Notification.count({ where: { status: 'unread' } }).then((notification) => {
if (notification) {
const dashNotification = req.notification;
return dashNotification;
}
});
},

How to redirect/render to 404 if the "_id" is wrong/misspelled in /blogs/:blogId

I want to redirect users to "404.ejs" if the post id is entered wrong/mispelled in blogs/:blogId route. How can I accomplish it in below code.
app.get('/blogs/:blogid', (req, res) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
console.log(err);
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
}
Code for "404"
app.get('*', (req, res) => {
res.render('404');
})
You should make use of express next parameter to get the result you want.
This will call the next "matching" middleware for the current route, assuming this would be your error handler middleware of course.
It should be used as shown below :
app.get('/blogs/:blogid', (req, res, next) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
next();
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
Express doc : https://expressjs.com/en/guide/using-middleware.html
app.get('/blogs/:blogid', async (req, res) => {
const requestedId = req.params.blogid;
const blog = await Blog.findById(requestedId);
if (!blog) return res.render("404");
res.render("post");
}
to check if the blog is null or not.

how to properly inject middleware in NodeJS route

How can i inject my middleware function 'checkAuthenticated' into my get route below?
not sure how to properly inject the code below. Please let me know. thank you very much.
function checkAuthenticated(req, res, next) {
if(!req.header('authorization')) {
return res.status(401).send({message: 'Unauthorized request. Missing authentication header'});
}
let token = req.header('authorization').split(' ')[1];
let payload = jwt.decode(token, '123');
if(!payload) {
return res.status(401).send({message: 'Unauthorized request. Authetication header invalid'});
}
req.user = payload;
next();
}
router.route('/:user_id')
.get((req, res) => {
User.findById(req.params.user_id, (err, user) => {
if (err) {
res.send(err);
} else {
res.json(user);
}
});
})
There are a few options here. I typically use:
router.use('*', checkAuthenticated);
Another option is:
router.get('/:user_id', checkAuthenticated, (req, res) => { ... })
Or, using your example of router.route...:
router.route('/:user_id').get(checkAuthenticated, (req, res) => { ... })
You can also chain them together:
router.route('/:user_id').get(checkAuthenticated).get((req, res) => { ... })
check this hope it will help you
router.route('/:user_id')
.all((req, res, next) => {
if (req.user) {
next();
} else {
res.redirect('/');
}
})
.get((req, res) => {
res.json(req.user);
});

many functions in one middleware expressjs restful api

I have a doubt about middelware in express.
I want to many thinks in one middleware. For example
I have this code y me middleware
module.exports = function(req,res,next) {
if(req.method === 'GET') {
res.end('GET method not supported');
} else {
next();
}
};
and I use it like this
app.route('/', <the_middleware>, (res, req, next) => {
// Code
})
But I am wondering if is possible to do something like this
app.route('/', <the_middleware>.<the function1>, (res, req, next) => {
// Code
})
app.route('/', <the_middleware>.<the_function2>, (res, req, next) => {
// Code
})
is there a possiblitity to do something like
function function1 (req,res,next) {
if(req.method === 'GET') {
res.end('GET method not supported');
} else {
next();
}
};
function function2 (req,res,next) {
if(req.method === 'GET') {
res.end('GET method not supported');
} else {
next();
}
};
module.exports = <I don`t know what go here>
Thanks.
Update. IT works, my code now is
The router
router.post('/', checkAuth.sayHi, checkAuth.sayBye, (req, res, next) => {
console.log('good');
res.status(200).send('it works');
console.log('yes');
});
The middleware
module.exports = {
sayHi(req, res, next) {
console.log('hi');
next();
},
sayBye(req, res, next) {
console.log('bye')
next();
}
};
You can just export an object containing both functions:
module.exports = {
function1,
function2
}

How to reuse database controllers

I'm trying to reuse my controllers which handle database operations. I'm bit struggling with structuring my application. Here's what I have:
server.js
var apiController = require('./controllers/api');
router.get('/cars', function (req, res) {
// get all cars from DB and render view
apiController.getCars().then(function (cars) {
res.render('index', {cars: cars});
});
});
router.get('/api/cars', function (req, res) {
// get all cars from DB and return JSON
apiController.getCars().then(function (cars) {
res.json(cars);
});
});
controllers/api.js
module.exports = {
getCars: function () {
db.collection('cars').find().toArray( function (err, cars) {
if (err) throw err;
return cars;
});
},
// tried also something like this but this doesn't really work
// for my use case because I don't want to attach any particular
// res to the function
getCars: function (req, res, next) {
db.collection('cars').find().toArray( function (err, cars) {
if (err) throw err;
res.json(cars);
});
},
};
Your current problem is that you expect promises as return in server.js while you use callbacks in the controller. I suggest you change your function getCars to return a Promise. Don't know what ODM/ORM you're using but it might look like something like this:
getCars: function () {
return db.collection('cars').find();
},
server.js
var apiController = require('./controllers/api');
router.get('/cars', function (req, res) {
apiController.get('cars').then(function (cars) {
res.render('index', {cars: cars});
});
});
router.get('/api/cars', function (req, res) {
apiController.get('cars').then(function (cars) {
res.json(cars);
});
});
controllers/api.js
var Promise = require('bluebird');
module.exports = {
get: function (modelName) {
return new Promise(function(resolve,reject){
return db.collection(modelName).find().toArray(function(err, models){
if (err) {
return reject(err);
}
else {
return resolve(models);
}
});
});
}
};
server.js
var apiController = require('./controllers/api');
router.get('/cars', apiController.getCars);
controllers/api.js
function getCarsAsync(req, res, next){
db.collection('cars').find().then(function(carsData){
if(carsData){
return res.send(carsData);
}
else{
return res.status(401).send('User is not authorized');
}
}).catch(function(err){
return next(err);
});
}
module.exports = {
getCars: getCarsAsync
};

Resources