使用Angular和Node.js / Express,是否有办法防止直接访问我的部分.html文件,同时仍然允许以下路由处理:
我的Angular路线如下所示:
$stateProvider.state('albums',{ url: '/albums',templateUrl: '/public/albums',controller: 'AlbumsCtrl' });
然后我的快递应用程序执行以下操作
app.get('/public/albums',function(req,res){ res.sendfile('views/partials/albums.html'); });
这一切都正常,但输入“mysite.com/public/albums”可以访问部分.html文件.
仍然没有任何东西可以看,因为内容是单独加载的,用户需要为此登录,但我仍然希望以某种方式阻止访问此文件.
解决方法
您可能自己找到了答案或不同的方法,但如果您想做类似的事情,实际上有一种解决方法:
这个想法
您可以使用httpRequestInterceptor在来自angular的所有请求上添加自定义标头.
在服务器端,您只需检查请求是否包含该标头.如果没有,则可以重定向或发送错误消息.
客户端(Angularjs):
创建一个拦截器:
myApp.factory('httpRequestInterceptor',function () { return { request: function (config) { config.headers['x-custom-header-name'] = 'something' return config } } });
myApp.config( function ($httpProvider) { $httpProvider.interceptors.push('httpRequestInterceptor') });
服务器端(node.js)
当您想要开始避免直接访问时,只需输入以下代码:
app.use(function (req,res,next) { if (!req.headers['x-custom-header-name']) { res.redirect('/'); //Or just do what you want to } next(); });
或者,如果您想避免仅在一条或某些路线上进行访问,则可以修改代码更改
app.use(function (req,next) ...
同
app.use( 'route/no-direct-access',function (req,next) ...
Setting application wide HTTP headers in AngularJS
希望这可以帮助别人!再见!