简体   繁体   English

router.get没有参数但要求参数

[英]router.get without parameter but asking for param

I am trying to use express nodejs and JWT. 我正在尝试使用express nodejs和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. 我保护所有路由,除了我在jwt.js文件中声明的路由。

  1. the '/trial' url, is not protected. '/trial'网址不受保护。 The controller is inside the trial.controller.js file. 控制器位于trial.controller.js文件中。 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. 当我点击postman中的url时,使用getpost方法并且没有任何auth( No Auth ),我得到了我期望的结果。
  2. But, the same things do not happen when I hit '/users/testdata' . 但是,当我点击'/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. 它没有受到保护,但如果我使用get方法并且没有任何auth,它会在邮递员中返回error 500 ,并显示消息"Cannot read property 'sub' of undefined" But, when I hit it with the post method, I get what I expect. 但是,当我用post方法点击它时,我得到了我期望的结果。

So, what's wrong with the get method? 那么, get方法有什么问题?

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); 出现问题的原因是路由router.get('/:id', getById); is defined before the route router.get('/testdata', getTest); 在路由router.get('/testdata', getTest);之前定义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. 因此,当您对/testdata路由执行请求时,它由/:id路由处理,需要身份验证才能工作,并使用currentUser.sub属性,尽管currentUser变量当前未定义。

Just change the order from 只需更改订单即可

router.get('/:id', getById);
router.get('/testdata', getTest);

to

router.get('/testdata', getTest);
router.get('/:id', getById);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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