Express js – 不能redirect

我正在尝试执行以下操作:

来自客户

var req = jQuery.post( "http://www.example.com:3000"+"/dologin", {"username" : username, "password" : password}).error(function(){ alert("an error occurred"); }); 

在expression根

 app.post('/dologin',function(req, res) { res.redirect('http://bbc.co.uk'); }); 

结果传回去了

 <p>Moved Temporarily. Redirecting to <a href="http://bbc.co.uk">http://bbc.co.uk</a></p> 

似乎如果我从jQuery发布redirect将无法正常工作。 有谁知道一种方法来强制它redirect?

浏览器不会redirectajax响应上的redirect窗口。 用JavaScriptredirect浏览器。

例如,在服务器发送新的网站作为内容。

 res.contentType('application/json'); var data = JSON.stringify('http://site.example.com/') res.header('Content-Length', data.length); res.end(data); 

在客户端

 var req = jQuery.post( "http://www.mysite.com:3000"+"/dologin", {"username" : username, "password" : password}, 'json').error(function(){ alert("an error occurred"); }).success(function(data) { window.location = data; }); 

开发应用程序时,我实际上遇到了同样的情况。 看来如果这个方法是post,Express不会redirect。

尝试:

 app.post('/dologin',function(req, res) { req.method = 'get'; res.redirect('http://bbc.co.uk'); }); 

在使用OAuth2时,我正在做这样的事情。 我有一个链接到我的网页之一,这反过来redirect到谷歌。

要redirect到另一个位置,下面的代码会执行实际的redirect

 app.get('/GoogleRequestAuthorization.html',function(req,res) { . . . . res.writeHead(302, {location: url}); res.end(); 

});

url是您要redirect到的地址。

全function是…

我遇到了类似的问题,并通过检查请求的types来解决这个问题。 在我的情况下,我使用JSON,但它也适用于其他POST请求:

  var ajax = req.xhr; if(ajax) { res.status(401).json({'msg':'redirect','location':'/login'}); } else { req.method = 'get'; res.status(401).redirect('/login'); //Or if you prefer plain text //res.status(333).send("Redirect"); } 

这可以处理Ajax POST和AJAX以及标准的GET请求。 在客户端,在Ajax resposecallback中:

 $.ajax({ type: 'POST', data: Msg, url: '/some/post', dataType: 'JSON' }).success(function(data, textStatus, req ) { if(data.msg==="redirect") window.location = data.location; else {...} }).error(function(data, textStatus, req) { if(req=="Unauthorized") { alert("Unauthorized!"); window.location = "/login"; } else if (data.responseJSON.msg==="redirect") window.location = data.responseJSON.location; else { //... } }); 

实际上你可以在这里处理更多的状态,除了302,JQuery自动跟随,你从你想要redirect到的页面作为响应200。 所以我避免发送302,发送401在我的情况下,或任何其他状态,例如333,这将被视为error handling。