我怎样才能限制访问只有Ajax请求?

我用ajax请求加载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请求的访问和redirect到404错误页如果不是ajax请求

有了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来使用上面的模式)

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

您可以覆盖.ajax()调用的beforeSend事件。 根据文档,您可以将自定义标题添加到请求。 这篇文章举了一个例子。

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