javascript - how can i restrict the access to only ajax requests? - Stack Overflow

i load inicio.jade with ajax req$.ajax({url:'inicio',cache: false,type: 'GET',})

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744092846a4557402.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信