3

i load inicio.jade with ajax req

$.ajax(
{
    url:'/inicio',
    cache: false,
    type: 'GET',
}).done(function(web)
{
    $('#contenido_nav_principal').fadeOut(600,function()
    {
        $('#contenido_nav_principal').empty();
        $('#contenido_nav_principal').html(web);
        $('#navegacion').animate({height:'600px'},200);
        $('#contenido_nav_principal').fadeIn(600);
    });
});

from this address in the server

app.get('/inicio',routes.inicio.inicio);

the problem is that i can access to the page with http://www.mypage.com/inicio

how can i restrict the access only to ajax requests and redirect to 404 error page if is not an ajax request

andrescabana86
  • 1,758
  • 8
  • 30
  • 50

3 Answers3

9

With expressjs, you can respond only to xhr requests like this:

function handleOnlyXhr(req, res, next) {
  if (!req.xhr) return next();
  res.send({ "answer": "only is sent with xhr requests"});
}

(in your example, routes.inicio.inicio would use the pattern above by checking req.xhr)

hunterloftis
  • 11,934
  • 5
  • 40
  • 45
2

You can detect whether it is an Ajax request at the server side by checking HTTP_X_REQUESTED_WITH header. The value of HTTP_X_REQUESTED_WITH header should be XmlHttpRequest if it is an Ajax request.

Stanley
  • 4,769
  • 3
  • 30
  • 44
0

You could override the beforeSend event on the .ajax() call. Per the documentation you can add custom headers to the request. This post gives an example.

Then you can have your page check for the presence of that custom header.

Community
  • 1
  • 1
Jason Whitted
  • 3,919
  • 1
  • 14
  • 15
  • That will stop casual users, but there are browser extensions that allow you to add custom headers in at least Firefox and Chrome. – Gort the Robot Dec 31 '12 at 03:12
  • @StevenBurnap So what you are saying is that if someone is bound and determined to go to that URL they can reverse engineer what you are doing and get access to it? Really?! – Jason Whitted Dec 31 '12 at 03:16