passing data to partial express js hbs - node.js

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;
}
});
},

Related

Failed to load resource: the server responded with a status of 403 (Forbidden) (Node.js)

So I'm trying to fetch some data from my backend and I get this error. It's wierd because until a few days ago it worked just fine.
Failed to load resource: the server responded with a status of 403 (Forbidden)
Also this is my backend code:
verifyToken.js
const jwt = require('jsonwebtoken');
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if (err) res.status(403).json('Token is not valid!');
req.user = user;
next();
});
} else {
return res.status(401).json('You are not authenticated!');
}
};
const verifyTokenAndAuthorization = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.id === req.params.id || req.user.isAdmin) {
next();
} else {
res.status(403).json('You are not alowed to do that!');
}
});
};
const verifyTokenAndAdmin = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.isAdmin) {
next();
} else {
res.status(403).json('You are not alowed to do that!');
}
});
};
module.exports = {
verifyToken,
verifyTokenAndAuthorization,
verifyTokenAndAdmin,
};
What should I do to fix it?

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
}

middleware is not working in nodejs

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.

Resources