简体   繁体   中英

nodejs express res.render in ajax calls

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');
});

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() .

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'));
       });
    });

Step-1: Make a public URL, say http://your-web-site.com/redirect_destination.html

Step-2: On making ajax request from front-end, redirect user to that page using .redirect() method on response

EDIT:

The point is, I don't think it's possible to render page by making an ajax request. You can prepare a URL which renders your desired page and redirect user to that URL using .redirect() method.

Usually ajax is used to update a portion of page using some resposne from server without refreshing page. If you want to navigate to another route instead of ajax use form submits or href . If you stick to ajax then return a JSON from the server and do the alteration using javascript

requestHandler=(req,res)=>{
 res.json({data:{}})
}

Your router will not render page ,it will send only response and I didnt get just for page rendering, why you are calling ajax request on click event.If dont mind you can write logic on click and change window.location with your router. It will render particular page, for that your router should be something like this:

    // about page route (http://localhost:8080/about)
    router.get('/about',isAuthenticated, function(req, res) {
        res.sendFile(path.join(__dirname+'/public/about.html'));
    }); 

   function isAuthenticated(req, res, next) {
  // do any checks you want to in here

  // CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
  // you can do this however you want with whatever variables you set up
  if (req.user.authenticated)
      return next();

  // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
  res.redirect('/');
 }

And change your url on click to http://localhost:8080/about

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.

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.

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM