NodeJS,Express显示来自AJAX POST的HTML页面响应

将NodeJS与Express服务器一起使用时,当您转到http:// localhost:(Serverport)时 , NodeJS服务器会使用以下代码发送HTML文件进行响应:

app.get('/', function(req, res){ res.sendFile(__dirname + '/login.html'); }); 

现在我正在使用JQuery AJAX POST向服务器发送信息,并根据服务器响应将用户发送到HTML页面“/ index”,或者如果用户凭据不好,HTML页面“/ loginno”。 问题是AJAX不像在服务器获取函数响应中一样玩sendfile的服务器响应。

我从服务器获取文件,并在控制台中输出完整的HTML,但我不知道如何使浏览器以与服务器GET响应相同的方式进入页面。

这是我的Ajax函数,它可以从服务器获取HTML页面对象,但浏览器不会导航到页面。

 $.ajax({ type: "POST", url: '/index', //A string containing the URL to which the request is sent. timeout: 2000, //A plain object or string that is sent to the server with the request. data: userdata, //The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). dataType: 'html', success: function(response,status,xhr) { //show content console.log('Success!' + response+', Status: '+status+', xhr: '+xhr) }, error: function(jqXHR, textStatus, err) { //show error message alert('text status '+textStatus+', err '+err) } }); 

所以问题是,你如何告诉JQuery AJAX POST函数导航到从NodeJS服务器响应发送的HTML页面对象?

看了这个问题的答案… 通过Ajax调用Response.redirect

我能够通过构build一个带有urlvariables的json响应,并在ajax post成功的情况下做到我所需要的东西,testing一下服务器是否可以转到新页面并使用window.location.href进行导航。

在我的NodeJS服务器路由…

 app.post('/index', function(req, res) { //Do some req verification stuff here //If req verfiication passes var servResp = {}; servResp.success = true; servResp.redirect = true; servResp.redirectURL = "http://localhost:3000/index"; res.send(servResp); }); 

和我的AJAX Postfunction…

 $.ajax({ type: "POST", url: '/index', //A string containing the URL to which the request is sent. timeout: 2000, //A plain object or string that is sent to the server with the request. data: userdata, //The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). dataType: 'json', success: function(response,status,xhr) { //show content console.log('Success!' + response+', Status: '+status+', xhr: '+xhr) if(response.redirect) { window.location = response.redirectURL; } }, error: function(jqXHR, textStatus, err) { //show error message alert('text status '+textStatus+', err '+err) } }); 

感谢所有帮助过的人!