Error return value, Nodejs, JWT - node.js

function isTokened(data) {
var token = data;
if(token != null || token != undefined){
jwt.verify(token, app.get('userToken'), function(err, decoded) {
return {
"user": decoded._doc.name,
"href": "/salir",
"text": "Salir"
};
});
}else{
return {
href: "/entrar",
text: "Entrar"
};
}
}
TypeError: c:\Users\Hector\Desktop\Proyecto\views\index.jade:81
79| li 80|
a.text(href='/acerca') Acerca
81| if au.user 82| li 83| a.text(href="/area") #{au.user} 84|
li
Cannot read property 'user' of undefined at eval (eval at
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:218:8),
:354:8) at eval (eval at
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:218:8),
:453:22) at exports.compile.res
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:219:38)
at Object.exports.renderFile
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:380:38)
at Object.exports.renderFile
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:370:21)
at View.exports.__express [as engine]
(c:\Users\Hector\Desktop\Proyecto\node_modules\jade\lib\index.js:417:11)
at View.render
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\view.js:126:8)
at tryRender
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\application.js:639:10)
at EventEmitter.render
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\application.js:591:3)
at ServerResponse.render
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\response.js:961:7)
at c:\Users\Hector\Desktop\Proyecto\app.js:167:6 at Layer.handle
[as handle_request]
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\router\layer.js:95:5)
at next
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request]
(c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\router\layer.js:95:5)
at
c:\Users\Hector\Desktop\Proyecto\node_modules\express\lib\router\index.js:277:22

jwt.verify is not a sync function so your function ends up exiting without returning anything. You need to use callback approach to get verify result. You want something like this:
function isTokened(data, callback) {
if(data){
jwt.verify(data, app.get('userToken'), function(err, decoded) {
callback && callback({
"user": decoded._doc.name,
"href": "/salir",
"text": "Salir"
});
});
}else{
callback && callback({
href: "/entrar",
text: "Entrar"
});
}
}
You will probably want to do some error handling in case jwt.verify returns an error or decoded does not contain required fields.

Related

"message": "Cannot read properties of undefined (reading 'split')",

"message": "Cannot read properties of undefined (reading 'split')",
+ "stack": "TypeError: Cannot read properties of undefined (reading 'split')
+ at /Users/dhruv/code/c0485f/src/api/posts.js:66:31
+ at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5)
+ at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:144:13)
+ at Route.dispatch (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:114:3)
+ at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5)
+ at /Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:284:15
+ at Function.process_params (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:346:12)
+ at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:280:10)
+ at Function.handle (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:175:3)
+ at router (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:47:12)",
I am getting this error from the code attached below and while calling this API there is data in body "authorIds"
router.get('/', async (req, res, next) => {
try {
const { authorIds, sortBy = 'id', direction = 'asc' } = req.body;
//if access token is not verified then this statemnt will throw an error.
jwt.verify(req.headers['x-access-token'], process.env.SESSION_SECRET);
//finding all posts which all are associated with authorIds got from request.
const posts = await Post.findAll({
order: [[sortBy, direction]],
include: [
{
model: UserPost,
required: true,
attributes: [],
where: {
userId: authorIds.split(","),
},
},
],
});
//console.log(posts);
res.json({ posts });
} catch (error) {
if (error.name === 'JsonWebTokenError') {
return res.status(401).json({ error: error.message });
}
next(error);
}
});
make sure you are sending the authorIds in request body and its value is valid and make sure you use express.json() middleware in your express app at the start so it can parse the body.
app.use(express.json());
and one more thing
you are trying to read request body from a get request!
get request cant carry a body, only query param and path param and headers are allowed.
turn it to a post request or send params in query or path.

Unable to grab data from MongoDB to use on Express

I'm currently trying to grab data from MongoDB via Mongoose, and show it with Express. However, this is the following error I'm getting:
TypeError: /home/node/CSci-Project/views/account.ejs:31
29| <% if (req.user.twitter.token) { %>
30| <p>
>> 31| <strong>id</strong>: <%= user.twitter.id %><br>
32| <strong>token</strong>: <%= user.twitter.token %><br>
33| <strong>display name</strong>: <%= profile.twitter.displayName %><br>
34| <strong>username</strong>: <%= profile.twitter.username %><br>
Cannot read property 'twitter' of undefined
at eval (/home/node/CSci-Project/views/account.ejs:13:31)
at account (/home/node/CSci-Project/node_modules/ejs/lib/ejs.js:691:17)
at tryHandleCache (/home/node/CSci-Project/node_modules/ejs/lib/ejs.js:272:36)
at View.exports.renderFile [as engine] (/home/node/CSci-Project/node_modules/ejs/lib/ejs.js:489:10)
at View.render (/home/node/CSci-Project/node_modules/express/lib/view.js:135:8)
at tryRender (/home/node/CSci-Project/node_modules/express/lib/application.js:640:10)
at Function.render (/home/node/CSci-Project/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/home/node/CSci-Project/node_modules/express/lib/response.js:1012:7)
at /home/node/CSci-Project/app/routes.js:67:13
at Layer.handle [as handle_request] (/home/node/CSci-Project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/node/CSci-Project/node_modules/express/lib/router/route.js:137:13)
at isLoggedIn (/home/node/CSci-Project/app/routes.js:105:16)
at Layer.handle [as handle_request] (/home/node/CSci-Project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/node/CSci-Project/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/node/CSci-Project/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/node/CSci-Project/node_modules/express/lib/router/layer.js:95:5)
I thought I had passed it through with callback and with findOne being asynchronous, so I'm not sure where to go from here. Here are the relevant files:
views/account.ejs (the page I'm trying to view)
app/routes.js
app/models/user.js
app/models/profile.js
Sorry if I've made any simple mistakes in here - I'm new to Node and I've come over from C#, so I'm still in the process of learning the differences. Also worth noting that data is definitely on MongoDB and it all exists.
Well, I managed to figure it out, after countless attempts. My mistake was that I thought by putting var userInfo = UserModel.findOne it would just simply print itself out as userInfo.id, userInfo.token, etc, but no. I actually meant to use the output that's inside of UserModel.findOne.
app/routes.js
module.exports = function (app, passport) {
app.get('/account', isLoggedIn, function (req, res) {
var UserModel = require('./models/user.js');
var ProfileModel = require('./models/profile.js');
UserModel.findOne({
'twitter.id': req.user.twitter.id
}, function (err, userInfo) {
if (err) {
return res.redirect('/');
} else {
ProfileModel.findOne({
'twitter.id': req.user.twitter.id
}, function (err, profileInfo) {
if (err) {
return res.redirect('/');
} else {
res.render('account.ejs', {
req: req,
user: userInfo,
profile: profileInfo
});
}
});
}
});
});
};

EJS: ReferenceError: bot is not defined

I want to make a bot dashboard in Discord.js and EJS.
I have an error.
>> 1| <%- include('blocks/header', {bot, user, path})%>
bot is not defined
at eval (/app/dashboard/index.ejs:10:43)
at index (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:682:17)
at tryHandleCache (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:254:36)
at View.exports.renderFile [as engine] (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/ejs/2.7.4/node_modules/ejs/lib/ejs.js:485:10)
at View.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/view.js:135:8)
at tryRender (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/application.js:640:10)
at Function.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/response.js:1012:7)
at app.get (/app/util/dashboard.js:45:7)
at Layer.handle [as handle_request] (/rbd/pnpm-volume/694e46f9-27bb-4ad9-87e8-c675e51f8f94/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/layer.js:95:5)
But I have it defined.
const renderTemplate = (res, req, template, data = {}) => {
const baseData = {
bot: client,
path: req.path,
user: req.isAuthenticated() ? req.user : null
};
res.render(templateDir + path.sep + template, {baseData, data});
};
I have a include tag in my index.ejs file.
<%- include('blocks/header', {bot, user, path})%>
For any help, thank you!
The way around this would be to render it differently;
const renderTemplate = (res, req, template, data = {}) => {
res.render(templateDir + path.sep + template), {
bot: client,
path: req.path,
user: req.isAuthenticated() ? req.user : null
data: data
})
};

strange behavior jsonwebtoken expired error

I have a Node.js application which uses jsonwebtoken for session management.
However, after the token expired, when I want to access again, I got:
{ TokenExpiredError: jwt expired
at Object.module.exports [as verify] (/home/ubuntu/me-n-you/node_modules/jsonwebtoken/verify.js:126:19)
at auth (/home/ubuntu/me-n-you/app_server/routes/index.js:14:9)
at Layer.handle [as handle_request] (/home/ubuntu/me-n-you/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/me-n-you/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/me-n-you/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/me-n-you/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:174:3)
at router (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/home/ubuntu/me-n-you/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:317:13)
at /home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/me-n-you/node_modules/express/lib/router/index.js:275:10)
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 2018-05-08T21:14:27.000Z }
I repeat to get the same errors until a very long time then I could access again.
But, I can access if using another device or browser at the same time.
I have no idea how to fix it. Does anyone have any clue on this?
Thanks in advance.
Richard Xu
You can again logged in ,also if you are using bcrypt
bcrypt.compare(req.body.password, data[0].password, (err, resposne) => {
if (err) {
res.status(500).json(err);
}
//response is either true or false
if (resposne) {
const token = jwt.sign({
email: data[0].email,
userId: data[0]._id
}, "secret",
{
expiresIn: "1h"
})
return res.status(200).json({
message: 'Auth successful',
token: token
})
} else {
return res.status(401).json({ message: 'Auth failed' })
}
})
Increase your expiry limit

Cannot read property 'prototype' of undefined

I'm starting with Parse and Node.js. I'm trying to retrieve data from Parse db and I don't manage to.
var Parse = require('parse').Parse;
Parse.initialize("*************", "*****************");
module.exports = {
index: function(req, res, next){
var query = new Parse.Query(Parse.Event);
query.find({
success: function(results) {
console.log(results);
},
error: function(error) {
console.log(error.message);
}
});
}
}
And I got this error :
TypeError: Cannot read property 'prototype' of undefined
at Object.Parse.Query (/Users/tchiss_a/test/webapp/node_modules/parse/build/parse-latest.js:7771:33)
at module.exports.index (/Users/tchiss_a/test/webapp/api/Events.js:7:20)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/layer.js:82:5)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:235:24
at Function.proto.process_params (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:313:12)
at /Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/Users/tchiss_a/test/webapp/node_modules/express/lib/router/index.js:296:3)
Can someone help me please ?
There is a fix listed in the comments, but the actual problem here is that you're treating a user-defined class "Event" like a Parse class.
change
var query = new Parse.Query(Parse.Event);
to
var query = new Parse.Query("Event");

Resources