How to access cookies in handlebars? - node.js

I want to check in home page that user is logged in or not. I have stored jwt token in cookies. For authentication I want to use cookies in handlebars.

Try this code:
Controller
const express = require('express');
const { engine } = require('express-handlebars');
var cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
const isLogin = checkLogin(req.cookies.jwt); // Check login here
res.render('home', { isLogin });
});
View
<h1>{{ isLogin }}</h1>

Related

I have a server error from using ejs template

I have reviewed this question but I could not solve the problem
Nodejs/Express: Error: Failed to lookup view "error" in views directory
I have these server setup
const express = require('express');
var jquery = require('jquery');
var admin = require("firebase");
var bodyParser = require('body-parser')
const app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.get('/login', function (req, res) {
res.render('login');
})
when I run the server this is the error I get
>>Error: Failed to lookup view "login" in views directory
what am I doing wrongly?

POST not working while using express + bootstrap modal

I made a register form using the bootstrap modal and I can't seem to make the POST request work.
This is the form in my en.pug file
#register.modal.fade(tabindex="-1" role="dialog" aria-labelledby="register form" aria-hidden="true")
.modal-dialog(role="document")
.modal-content
.modal-header
h5#exampleModalLabel.modal-title Sign Up
button.close(type="button" data-dismiss="modal" aria-label="Close")
span(aria-hidden="true") ×
.modal-body
form(action='/register' method='POST' )
.form-group
label.form-control-label(for="name") Name:
input#name.form-control(type="text", placeholder='first and last' name='name')
.form-group
label.form-control-label(for="email") Email:
input#email.form-control(type="email", placeholder='name#email.com', name='email')
.form-group
label.form-control-label(for="password") Password:
input#password.form-control(type="password" name='password')
.form-group
label.form-control-label(for="password") Confirm Password:
input#confirmed-password.form-control(type="password" name='confirmPassword')
hr.mb-4
// /registration form
.modal-footer
button.btn.btn-secondary(type="button" data-dismiss="modal") Close
button.btn.btn-primary(type="submit") Sign Up
This is my server.js file
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// serve static files from /public
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
// include routes
const routes = require('./routes/index');
app.use('/', routes);
app.listen(3000);
And this is the ./routes/index.js
var express = require('express');
const app = express();
var router = express.Router();
router.get('/', (req, res) => {
const cookie = req.cookies.language;
if (cookie) {
res.render('en', { cookie });
} else {
res.render('ro');
}
});
router.get('/en', function (req, res) {
res.cookie('language');
return res.render('en');
});
// GET /
router.get('/ro', function(req, res) {
res.clearCookie('language');
return res.render('ro');
});
app.post("/register", function (req, res) {
console.log('Hellooooooooooooooooo!')
});
module.exports = router;
When I fill out the form and press the Sign Up button I expect to show "Hellooooooooooooooooo!" in the console but nothing happens and I can't seem to figure out why. Am I missing something here?
EDIT: I figured out that I made a mistake in the pug indentation and the submit button was outside the form, reason for which completing the form and pressing the sign up button didn't do anything
You have to use bodyparser middleware.
We had to install body-parser before express version 4 update, but express now supports body-parser by default.
Just add
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Hope it helps.
In the HTML, in the input tags of the form of the bootstrap modal window, I used the name attribut (instead of the id attribute) and it is working.
//install body-parser npm and require it
const bodyParser = require('body-parser')
//write code below of app.use(cookieParser()) in server.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
router.post('/', function(req, res){
console.log(req.body) //here you will get POST data
})

NodeJs routes not working from inner page

I am trying to develop an application in NodeJs using express framework. My routing is working when I navigating from home to inner pages. But If I want to navigate from some inner page to homepage then it is not working.
Below is my app.js code.
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
//declare all routers
var home = require(path.join(__dirname, "/routes/index"));
var myaccount = require(path.join(__dirname, "/routes/myaccount"));
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', engines.handlebars);
var defaultViewPath = path.join(__dirname, "/views");
app.set('views', defaultViewPath);
app.set('view engine', 'html');
app.use('/', home);
app.use('/myaccount', myaccount);
Here if I have navigated from home to myaccount - Its working
But if I am navigating from myaacount to home - It reloads the same page.
Can anyone help me to resolve this issue.
To define routing using methods of the Express app object, use app.get() to handle GET requests
var express = require('express')
var app = express()
// When GET request is made to the homepage
app.get('/', function (req, res) {
res.render('home');
});
// When GET request is made to the myaccount
app.get('/myaccount', function (req, res) {
res.render('myaccount');
});
app.get('/myaccount/innerpage', function (req, res) {
res.send('Hello Inner Page');
});
//Page Not Found
app.use(function(req, res){
//render the html page
//res.render('404');
res.sendStatus(404);
});
Hope this could help you
use app.get and app.post Route Methods
app.get('/',function(req,res){
res.render('home');
});
app.get('/myaccount',function(req,res){
res.render('myaccount');
});
Or Create Router File For Home & myAccount
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Home Page')
})
module.exports = router
in Your app.js or index.js file , require route.js
var home = require('./route');
app.use('/', home)

Nodejs shows Error "Cannot GET /test"

I am trying to retrieve output on other url / directory in nodejs but it's Display Error ("Cannot GET /test").
Please Suggest me what i have to do to get my output on ("http://localhost:8080/test").
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/test');
}
});
app.listen(8080);
OutPut : Cannot GET /test
You did not specify a route for /test. You should have
app.get('/test', function(req, res, next){
res.render('test'); // This should have a view
});
Here i writing sample. create views folder in root folder and add one test.pub file to views then just run
Note:dont forget to install pug and express
var express = require('express')
var app = express()
app.set('view engine', 'pug');
app.set('views','./views');
// here am directly sending response without using view engine
app.get('/', function (req, res) {
res.send('hello world')
})
// here am sending response with using view engine
app.get('/test', function(req, res){
res.render('test');
});
app.listen(8000,function(){
console.log(" Server is running on port 8000");
});

Node.js ExpressJs Create Session

How can I create session in expressjs(4.0)?
I am doing exactly same in the links
var session = require('express-session');
/* session */
app.use(session({ secret: '1s2sd25asd7asd5asd7f4f1f'}))
However it gives error?
TypeError: Cannot read property 'connect.sid' of undefined
How do I create session in expressjs? I have been trying to create session for 3 days.
In express 4, create session like this
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
You have to must use cookieParser before session
app.use(cookieParser())
app.use(session({secret: 'MySecret'}));
for further information, read connect official documentation here
Complete code :
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({secret: 'ssshhhhh'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var sess;
app.get('/',function(req,res){
sess=req.session;
//Session set when user Request our app via URL
if(sess.email)
{
/*
* This line check Session existence.
* If it existed will do some action.
*/
res.redirect('/admin');
}
else{
res.render('index.html');
}
});
app.post('/login',function(req,res){
sess=req.session;
//In this we are assigning email to sess.email variable.
//email comes from HTML page.
sess.email=req.body.email;
res.end('done');
});
app.get('/admin',function(req,res){
sess=req.session;
if(sess.email)
{
res.write('
<h1>Hello '+sess.email+'</h1>
');
res.end('Logout');
}
else
{
res.write('
<h1>Please login first.</h1>
');
res.end('Login');
}
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
}
else
{
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
Read here : http://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/

Resources