William
William

Reputation: 1175

Importing a ejs file inside a div through jQuery

Alright, so I've been trying multiple strategies for this, and I seem to fall short, and I have no idea why, so I have this code here: (UPDATED script)

<script>
$(function(){
  $('#actions-view').load('views/game_snippets/actions.ejs');
});
</script>

Okay so I got it to work with this code in my nodejs app:

app.get('/actions.ejs', function(req, res){
  if (req.user) {
    res.render('actions');
  } else {
    res.redirect('/');
  }
});

The only issue with this is, is someone can go to the specified route and it would show just the rendered html. I am curious if nodejs has a function for this exact purpose.

Upvotes: 0

Views: 34

Answers (1)

Adrian
Adrian

Reputation: 8597

As you have fixed your original issue, you can check if the request was an Ajax request before serving the file.

Most frameworks (I believe JQuery does and AngularJs definitely doesn't) set a header in the request called X-Requested-With.

To check in your code, you would wrap req.xhr inside an if statement.

Obviously if the request is not an Ajax call youll get undefined.

Upvotes: 1

Related Questions