Change URL after POST using ExpressJS

╄→尐↘猪︶ㄣ 提交于 2020-01-01 09:38:05

问题


I use expressJS as my NodeJS server. The user sends me his login info through a POST and after checking the credentials I render a page:

router.post("/login", function (req: Request, res: Response, next) {
   if(credentialsOK){
      res.render('main');
   }
});

The problem is that the URL becomes http://myaddress/login and I would like to remove the /login of the address. I don't want to use redirect as I want to send local variables through the render.

How can I change the URL?


回答1:


You can still pass your local variables through res.redirect.

router.post("/login", function (req: Request, res: Response, next) {
   if(credentialsOK){
       req.session.localVar = yourLocalVar;
       res.redirect('/main');
   }
})

Then in main router:

router.get("/main", function (req: Request, res: Response, next) {
    var yourLocalVar = req.session.localVar;
    res.render('main');
})



回答2:


You cannot change the URL from the server side, but you can change the URL by using the javascript method window.history.pushState("", "", '/');

<script>
window.history.pushState("", "", '/');
</script>


来源:https://stackoverflow.com/questions/37425926/change-url-after-post-using-expressjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!