【问题标题】:Change URL after POST using ExpressJS使用 ExpressJS 在 POST 后更改 URL
【发布时间】:2016-05-25 00:17:12
【问题描述】:

我使用 expressJS 作为我的 NodeJS 服务器。用户通过 POST 向我发送他的登录信息,并在检查凭据后呈现页面:

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

问题是 URL 变成了http://myaddress/login,我想删除地址的 /login。我不想使用重定向,因为我想通过渲染发送局部变量。

如何更改网址?

【问题讨论】:

  • 为什么不在客户端使用 ajax 来发出请求,而只使用 res.json() 通过 ajax calll 将局部变量发送到客户端?或者您想渲染与渲染内容不同的“主要”?
  • @JoseHermosillaRodrigo main 与渲染的不同
  • 这样我认为你能做到的唯一方法就是在客户端中完成所有艰苦的工作,用从 ajax 调用接收到的数据来呈现你想要呈现的内容,我猜。

标签: node.js express


【解决方案1】:

您无法从服务器端更改 URL,但您可以更改 URL 通过使用javascript方法window.history.pushState("", "", '/');

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

【讨论】:

    【解决方案2】:

    您仍然可以通过res.redirect 传递您的局部变量。

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

    然后在main路由器:

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

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 1970-01-01
      • 2013-11-06
      • 2012-12-15
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多