3

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

4

3 回答 3

9

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

于 2012-12-31T03:12:14.483 回答
2

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

于 2012-12-31T03:09:12.293 回答
0

您可以覆盖通话中的beforeSend事件.ajax()。根据文档,您可以向请求添加自定义标头。 这篇文章给出了一个例子。

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

于 2012-12-31T03:07:46.613 回答