简体   繁体   中英

router.get without parameter but asking for param

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.

  1. the '/trial' url, is not protected. The controller is inside the trial.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.
  2. But, the same things do not happen when I hit '/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);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM