Reputation: 238
Hello when I try and redirect to my welcome page I get this type error. The TypeError is being called on my verifyToken.js file when trying to find the value of the req.cookies.auth_token
Also note that the index.js file has a lot of code that probably isn't relevant to this question but I added it to this question just to be safe and make sure I'm not missing anything obvious.
TypeError: Cannot read property 'auth_token' of undefined at module.exports (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\routes\verifyToken.js:10:39) at Layer.handle [as handle_request] (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\index.js:275:10) at urlencodedParser (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\body-parser\lib\types\urlencoded.js:91:7) at Layer.handle [as handle_request] (C:\Users\Likel\Documents\GitHub\Node.js_Authenticator\node_modules\express\lib\router\layer.js:95:5)
Here is my code
verifyToken.js
const jwt = require('jsonwebtoken');
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser());
module.exports = function (req,res,next){
const token = req.cookies.auth_token;
if (!token) {
return res.status(403).send('Access Denied');
}
try {
const data = jwt.verify(token, process.env.TOKEN_SECRET);
req.userId = data.id;
next();
} catch(err) {
return res.sendStatus(400).send('Invalid Token');
}
};
auth.js
//Login
router.post('/login', async (req,res) => {
const {error} = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if eamil exist in database
const user = await User.findOne({email: req.body.email});
if(!user) return res.status(400).send('Invalid Email');
//Check if password is correct
const validPass = await bcrypt.compare(req.body.password, user.password);
if(!validPass) return res.status(400).send('Invalid password')
//Creat and assign json web token
const token = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET);
return res
.cookie("auth_token", token, {
httpOnly: true,
secure: process.env.TOKEN_SECRET === "production",
})
.status(200),
res.redirect('/welcome');
});
module.exports = router;
index.js
const express = require('express');
const app = express();
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
//Import Routes
const authRoute = require('./routes/auth');
const postRoute = require('./routes/posts');
const res = require('express/lib/response');
const { verify } = require('jsonwebtoken');
const verifyJsonWebToken = require('./routes/verifyToken');
const { cookie } = require('express/lib/response');
dotenv.config();
//Set views
app.set('view-engine', 'ejs')
app.use(express.urlencoded({extended: false }))
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.get('/login', (req, res) => {
res.render('login.ejs')
});
app.get('/register', (req, res) => {
res.render('register.ejs')
});
app.get('/welcome', verifyJsonWebToken, (req, res) => {
res.render('welcome.ejs', { username: 'username'})
});
//Sends From Info to database
app.post('/register', authRoute);
app.post('/login', authRoute);
//Adds css to pages
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
//Connect to DB
mongoose.connect(
process.env.DB_CONNECT,
() => console.log('connected to db!')
);
//Middleware
app.use(cookieParser());
app.use(express.json());
//Route Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
app.listen(3000, () => console.log('Server Up and Running'));
Any help or suggestions would be appreciated thanks!
Upvotes: 0
Views: 134
Reputation: 219
I think you should try using app.use(cookieParser());
at beginning before using express routes.
Upvotes: 0