【问题标题】:how can i restrict the access to only ajax requests?我怎样才能限制对只有ajax请求的访问?
【发布时间】:2012-12-15 08:06:47
【问题描述】:

我用 ajax req 加载 inicio.jade

$.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);
    });
});

来自服务器中的这个地址

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

问题是我可以使用http://www.mypage.com/inicio访问页面

如果不是 ajax 请求,我如何限制仅访问 ajax 请求并重定向到 404 错误页面

【问题讨论】:

    标签: javascript ajax node.js express


    【解决方案1】:

    使用 expressjs,您只能像这样响应 xhr 请求:

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

    (在您的示例中,routes.inicio.inicio 将通过检查 req.xhr 来使用上述模式)

    【讨论】:

      【解决方案2】:

      在服务器端可以通过HTTP_X_REQUESTED_WITH header 检测是否是Ajax请求。如果是 Ajax 请求,HTTP_X_REQUESTED_WITH header 的值应该是XmlHttpRequest

      【讨论】:

        【解决方案3】:

        您可以在 .ajax() 调用上覆盖 beforeSend 事件。根据the documentation,您可以将自定义标头添加到请求中。 This post 举个例子。

        然后您可以让您的页面检查该自定义标题是否存在。

        【讨论】:

        • 这将阻止临时用户,但有一些浏览器扩展允许您至少在 Firefox 和 Chrome 中添加自定义标题。
        • @StevenBurnap 那么您的意思是,如果有人被绑定并决心访问该 URL,他们可以对您正在做的事情进行逆向工程并访问它?真的吗?!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-09
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        相关资源
        最近更新 更多