发送请求后重定向页面[快递4] [英] Redirect page after post request [Express 4]

查看:118
本文介绍了发送请求后重定向页面[快递4]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  / ** 
* @api {post} / logout从系统退出
* @apiName注销
* @apiGroup登录
* /
router.post(/ logout,function(req,res){
req.logout();
req.session.destroy();
return res .redirect(/);
});我已经读过 Node.js Express:如何在处理帖子请求后重定向页面,但无法弄清答案。 / p>

我最近更改了注销到POST而不是GET。这样做后,重定向不工作

  POST /注销307 4.912 ms  -  36 
POST / 302 3.922 ms - 23
GET / 200 7.519 ms - -

我可以在客户端手动,但我想知道如何在服务器端这样做。这是可能吗?



客户端



HTML

 < a href =javascript :;的onclick = 退出(); > 

JS

  function logOut(){
$ .post(/ logout);
}


解决方案

Javascript生成了您的 $。post()的Ajax调用。 Ajax发送请求,得到响应。一个ajax调用本身并不会改变页面位置。这是Ajax调用的特征。



当浏览器加载新页面时,重定向工作,服务器会将其更改为正在加载的新页面,而不是当浏览器发送Ajax呼叫。



当然,您可以使用客户端JavaScript来决定从客户端重定向到您的 $。post() code>完成。您甚至可以从 $。的回复。post()成为新的位置,然后您的客户端Javascript可以设置 window.location 到该新URL。

  function logOut(){
$ .post(注销)然后(function(data){
window.location = data.redirectUrl;
});
}

而且,在服务器上:

  router.post(/ logout,function(req,res){
req.logout();
req.session.destroy );
res.send({err:0,redirectUrl:/});
});


/**
 * @api {post} /logout Logout from system
 * @apiName Logout
 * @apiGroup Login
 */
router.post("/logout", function (req, res) {
  req.logout();
  req.session.destroy();
  return res.redirect("/");
});

I've read Node.js Express : How to redirect page after processing post request? but could not figure out the answer.

I recently changed logout to POST instead of GET. After doing so, redirect does'nt work

POST /logout 307 4.912 ms - 36
POST / 302 3.922 ms - 23
GET / 200 7.519 ms - -

I can manually do it on client side, but I want to know how to do it on server side as well. Is this possible?

CLIENT

HTML

<a href="javascript:;" onclick="logOut();">

JS

 function logOut() {
        $.post("/logout");
    }

解决方案

There are no redirects from a Javascript generated Ajax call which your $.post() is. Ajax sends a request, gets a response. An ajax call by itself does not change the page location at all. That's a characteristic of Ajax calls.

Redirects work when the browser is loading a new page and the server tells it to change what page it is loading to a new source, not when the browser just sends an Ajax call.

You can, of course, use your client-side Javascript to decide to redirect from the client side after your $.post() finishes. You could even have the response from the $.post() be the new location and your client-side Javascript could then just set window.location to that new URL.

function logOut() {
    $.post("/logout").then(function(data) {
        window.location = data.redirectUrl;
    });
}

And, on the server:

router.post("/logout", function (req, res) {
  req.logout();
  req.session.destroy();
  res.send({err: 0, redirectUrl: "/"});
});

这篇关于发送请求后重定向页面[快递4]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆