最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论