我如何限制只访问ajax请求?

时间:2012-12-31 02:56:20

标签: javascript ajax node.js express

我用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错误页面

3 个答案:

答案 0 :(得分:8)

使用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

来使用上述模式

答案 1 :(得分:2)

您可以通过选中HTTP_X_REQUESTED_WITH标头来检测它是否是服务器端的Ajax请求。如果它是Ajax请求,HTTP_X_REQUESTED_WITH标头的值应为XmlHttpRequest

答案 2 :(得分:0)

您可以覆盖beforeSend来电中的.ajax()事件。每the documentation您可以为请求添加自定义标头。 This post举了一个例子。

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