Node.js在Ajax调用中表达res.render [英] nodejs express res.render in ajax calls

查看:293
本文介绍了Node.js在Ajax调用中表达res.render的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在express.js中的res.render()有问题 我使用ajax在这条路线上进行请求:

i have a problem with res.render() in expressjs i use ajax to request on this route:

route.get('/about',authentication,(req,res)=>{
    res.render('about');
});

我进行了一些搜索,发现res.render不适用于ajax调用 所以如何在没有res.render()的情况下更改和呈现页面.

I did some search and found out that res.render does not work with ajax calls so how can I change and render page without res.render().

如果我删除res.renderconsole.log,它实际上可以在任何代码上工作,但不能运行res.render(通过单击链接,我在带有ajax请求的标头中发送令牌,然后在我的路由中有一个身份验证中间件获取令牌的用户,然后将用户重定向到about.ejs页面)

If I remove the res.render and console.log it it will work actually any code work but not res.render (by clicking a link I send a token in header with ajax request then in my route I have an authentication middleware that get the token then redirects the user to about.ejs page)

我只想更改页面.任何想法都会对你们有帮助. 谢谢 这是前端请求:

I just want to change the page. Any idea will help guys. thx here is the front-end request:

$(document).ready(function(){
       $('#about').click(function(){
         // window.location.href='/about';
           $.ajax({
              method:'get',
              url:'http://localhost:5000/about',
              headers:{"authtoken":localStorage.getItem('authToken')}
           }).done(()=>{
               // window.location.href='/about';
           }).catch(e=>console.log('header.ejs error'));
       });
    });

推荐答案

res.render使用模板组成一个html页面,并将最终的组合结果从服务器发送到客户端.它不会在客户端窗口中发布页面的呈现.

res.render composes a html page using templates and sends the final composed result from the server to the client. It does not issue a rendering of the page in the client window.

如果通过在浏览器的地址栏中输入URL发出请求,则浏览器将执行请求并呈现服务器发送的结果.

If the request is issued by entering the URL in the addressbar of the browser, then the browser will do the request and render the result the server sends.

如果执行ajax请求,您将收到该响应,但是您有责任在.done回调中对该响应进行处理.如果您执行ajax请求,浏览器将无法神奇地知道如何处理数据.并且由于您的.done回调中没有任何内容,因此不会发生任何事情.

If you do an ajax request you will receive that response, but you are responsible to do something with it in the .done callback. The browser does not magically know what has to be done with the data if you do an ajax request. And because you do not have anything in your .done callback nothing will happen.

所以您必须执行以下操作:

So you have to do something like that:

.done(response => {
    var bodyContent = response.match(/<body>(.*)<\/body>/)[1]
  $('body').html(bodyContent);
})

这篇关于Node.js在Ajax调用中表达res.render的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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