admin 管理员组

文章数量: 1086019

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

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

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./inicio

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

Share Improve this question asked Dec 31, 2012 at 2:56 andrescabana86andrescabana86 1,7888 gold badges32 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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)

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.

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.

本文标签: javascripthow can i restrict the access to only ajax requestsStack Overflow