I am trying to use express nodejs and JWT. Here is the source code of what I've been through: link.
I protect all routes, except routes that I declare inside the jwt.js file.
'/trial'
url, is not protected. The controller is inside thetrial.controller.js
file. When I hit the url in postman, both with the get
and the post
method and without any auth (No Auth
), I get what I expect.'/users/testdata'
. It's not protected, but if I hit it with the get
method and without any auth, it returns error 500
with the message "Cannot read property 'sub' of undefined"
in postman. But, when I hit it with the post
method, I get what I expect.So, what's wrong with the get
method?
Please see the above link for complete code. Any help will mean a lot to me. Thank you!
The problem occurs because the route router.get('/:id', getById);
is defined before the route router.get('/testdata', getTest);
. So when you perform a request to the /testdata
route, it is handled by the /:id
route, that requires authentication to work, and uses the currentUser.sub
attribute, although the currentUser
variable is currently undefined.
Just change the order from
router.get('/:id', getById);
router.get('/testdata', getTest);
to
router.get('/testdata', getTest);
router.get('/:id', getById);