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

and*_*a86 3 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);
    });
});
Run Code Online (Sandbox Code Playgroud)

从服务器中的这个地址

app.get('/inicio',routes.inicio.inicio);
Run Code Online (Sandbox Code Playgroud)

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

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

hun*_*tis 9

使用expressjs,您只能回复xhr请求,如下所示:

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

(在你的例子中,routes.inicio.inicio将通过检查使用上面的模式req.xhr)