如果您对PlayFramework2.1-AngularJS路由-最佳解决方案?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于PlayFramework2.1-Angula
如果您对Play Framework 2.1-AngularJS路由-最佳解决方案?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Play Framework 2.1-AngularJS路由-最佳解决方案?的详细内容,我们还将为您解答angularjs路由原理的相关问题,并且为您提供关于Angular2 (One framework 概要)、AngularJS + Django Rest Framework + CORS(CSRF Cookie未显示在客户端中)、AngularJS + Django Rest Framework + CORS(客户端未显示CSRF Cookie)、AngularJS iframe跨域打开内容时报错误的解决办法_AngularJS的有价值信息。
本文目录一览:- Play Framework 2.1-AngularJS路由-最佳解决方案?(angularjs路由原理)
- Angular2 (One framework 概要)
- AngularJS + Django Rest Framework + CORS(CSRF Cookie未显示在客户端中)
- AngularJS + Django Rest Framework + CORS(客户端未显示CSRF Cookie)
- AngularJS iframe跨域打开内容时报错误的解决办法_AngularJS
Play Framework 2.1-AngularJS路由-最佳解决方案?(angularjs路由原理)
我正在通过AngularJS教程进行工作。Angular使用它自己的JS路由机制来允许单页应用程序。Angular的示例路由文件如下所示:
angular.module('phonecat',[]).
config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/phones',{templateUrl: '/partials/phone-list',controller: PhoneListCtrl}).
when('/phones/:phoneId',{templateUrl: 'partials/phone-detail',controller: PhoneDetailCtrl}).
otherwise({redirectTo: '/phones'});
}]);
我试图找到一个存储我的局部文件(特定于Angular的HTML文件)的好地方。理想情况下,我希望能够从Play中对其进行模板化(例如,将其作为*
.scala.html文件)。我可以使用aa播放路由文件来完成此操作,如下所示:
GET /partials/phone_index controllers.Application.phone_index
我基本上偏向于这样的控制器动作:
def phone_index = Action {
Ok(views.html.partials.phone_index())
}
我正在寻找的解决方案是两种理想的结合:
- 我将进行某种映射,使我可以访问/ partial / *下的任何文件并取回部分文件。
- 我想重写路由到特定的部分,所以我 的CAN 用控制器动作来动态填充用数据(罕见)。
有任何想法吗?
Angular2 (One framework 概要)
Angular1.x 版本的火爆,我们不用多说,是很多前端工作者不错的选择,速度快,方便快捷,可拓展性强,我做过很多项目都是基于Anguar 1.x架构的。
但是Goolge公司在2.x版本,确做了新的设计,可以说和1.x版本是完全不同的,是一个崭新的框架,我们暂且不去评论它的好与坏, 我们先来看看,官方给出一个什么的解释。
Develop Across All Platforms
Learn one way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web,mobile web,native mobile and native desktop.
(其实,这个和1.x版本没有太大区别,html5的出生就是为了跨平台。)
Speed & Performance
Achieve the maximum speed possible on the Web Platform today,and take it further,via Web Workers and server-side rendering.
Angular puts you in control over scalability. Meet huge data requirements by building data models on RxJS,Immutable.js or another push-model.
(Angular 2.x 速度上会有很大提升,用过1.x版本都知道,Anguar的性能在某些方面并不是最好的,比如ng-repeat $watch等等,2.x 版本据说可以满足大数据量,并控制其伸缩性,这点值得我们去尝试。)
Incredible Tooling
Build features quickly with simple,declarative templates. Extend the template language with your own components and use a wide array of existing components. Get immediate Angular-specific help and Feedback with nearly every IDE and editor. All this comes together so you can focus on building amazing apps rather than trying to make the code work.
(对于Angular 2.x 版本,更多是基于component的,而且这个组件是可以自由拓展,这点像React的运行机制,这样的angular灵活性和拓展性会更加出色!)
loved by Millions
From prototype through global deployment,Angular delivers the productivity and scalable infrastructure that supports Google’s largest applications.
(Anguar做为一个开源框架,一直以来,就有很多的人在编写各种directive,方便我们直接使用,相信2.x版本,也是如此。)
AngularJS + Django Rest Framework + CORS(CSRF Cookie未显示在客户端中)
我正在使用AngularJS和Django Rest Framework + Django CORS Headers开发1页应用程序。
我的问题是,当我联系后端时,“ csrftoken” cookie永远不会显示在浏览器中。
例如:我正在使用帖子进行登录。我正确地获得了“ sessionid” cookie,但是“ csrftoken”却没有出现,因此我无法从客户端进行适当的发布,因为由于缺少csrf令牌而被拒绝了。
- 我已经分析了API的响应标头,而csrftoken却不是。
- 我直接在其余的API浏览器中查看,并且在那里显示得很好。
- 只是指出,我可以做我的第一个POST登录,因为Django Rest Framework只对经过身份验证的用户强制CSRF。如果我尝试重新登录,它将失败,因为它显示了“ sessionid” -cookie。
- 我对绕过CSRF的保护并不感兴趣,就像关于stackoverflow的一些帖子所建议的那样。
来自前端/后端的一些代码片段。这些都是未完成的代码段,因此请不要挂在编写拙劣的代码上。
后端API LoginView
class LoginView(APIView):renderer_classes = (JSONPRenderer, JSONRenderer)def post(self, request, format=None): serializer = LoginSerializer(data=request.DATA) if serializer.is_valid(): userAuth = authenticate(username=serializer.data[''username''], password=serializer.data[''password'']) if userAuth: if userAuth.is_active: login(request, userAuth) loggedInUser = AuthUserProfile.objects.get(pk=1) serializer = UserProfileSerializer(loggedInUser) user = [serializer.data, {''isLogged'': True}] else: user = {''isLogged'': False} return Response(user, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
客户端AngularJS登录控制器
.controller(''LoginCtrl'', [''$scope'', ''$http'', ''uService'', ''$rootScope'', function(scope, $http, User, rootScope) {scope.login = function() { var config = { method: ''POST'', withCredentials: true, url: rootScope.apiURL+''/user/login/'', data : scope.loginForm }; $http(config) .success(function(data, status, headers, config) { if (status == 200) { console.log(data[0]); //Test code // succefull login User.isLogged = true; User.username = data.username; } else { console.log(data); //Test code User.isLogged = false; User.username = ''''; } }) .error(function(data, status, headers, config) { console.log(''Testing console error''); User.isLogged = false; User.username = ''''; });};}]);
任何有好的技巧/想法/例子的人吗?
答案1
小编典典后端API LoginView(添加了一个强制将csrf令牌添加到主体的装饰器)
class LoginView(APIView):renderer_classes = (JSONPRenderer, JSONRenderer)@method_decorator(ensure_csrf_cookie)def post(self, request, format=None): c = {} c.update(csrf(request)) serializer = LoginSerializer(data=request.DATA) if serializer.is_valid(): userAuth = authenticate(username=serializer.data[''username''], password=serializer.data[''password'']) if userAuth: if userAuth.is_active: login(request, userAuth) loggedInUser = AuthUserProfile.objects.get(pk=1) serializer = UserProfileSerializer(loggedInUser) user = [serializer.data, {''isLogged'': True}] else: user = {''isLogged'': False} return Response(user, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
AngularJS客户端(将令牌添加到请求标头)
$http.defaults.headers.post[''X-CSRFToken''] = $cookies.csrftoken;
服务器端设置文件(专门用于django-cors-headers)
默认情况下会添加前5个,但你需要添加“ X-CSRFToken”以允许使用CORS从客户端到API的此类标头,否则该帖子将被拒绝。
CORS_ALLOW_HEADERS = (''x-requested-with'',''content-type'',''accept'',''origin'',''authorization'',''X-CSRFToken'')
答案2
小编典典子域A上的AngularJS单页Web应用程序,使用CORS和CSRF保护与子域B上的Django JSON(REST)API通讯
由于我目前正在进行类似的设置,并且正在努力使CORS与CSRF保护结合使用,因此我想在这里分享自己的经验。
设置 -SPA和API都位于同一域的不同子域上:
- 子域app.mydomain.com上的AngularJS(1.2.14)单页Web应用程序
- Django App(1.6.2)在子域api.mydomain.com上实现了JSON REST API
AngularJS应用通过与Django API APP相同的项目中的Django应用提供服务,因此它设置了CSRF Cookie。例如,另请参见如何从一个Django项目运行多个网站
Django API应用程序 -为了使CORS和CSRF保护正常工作,我需要在API后端执行以下操作。
在此应用程序的settings.py中(Django项目settings.py的扩展):
- 添加corsheaders应用程序和中间件以及CSRF中间件:
INSTALLED_APPS = ( ... ''corsheaders'', ...)MIDDLEWARE_CLASSES = ( ... ''django.middleware.csrf.CsrfViewMiddleware'', ... ''corsheaders.middleware.CorsMiddleware'',)
另请参阅GitHub上的Django CORS标头
将SPA Webapp的域添加到CORS_ORIGIN_WHITELIST
CORS_ORIGIN_WHITELIST = [ ... ''app.mydomain.com'', ...]
将CORS_ALLOW_CREDENTIALS设置为True。这很重要,如果您不这样做,则不会随请求一起发送CSRF Cookie
CORS_ALLOW_CREDENTIALS =真
将suresure_csrf_cookie装饰器添加到处理JSON API请求的视图中:
from django.views.decorators.csrf import ensure_csrf_cookie@ensure_csrf_cookiedef myResource(request): ...
AngularJS的Django应用程序 -AngularJS应用程序通过同一项目中的Django应用程序提供。此Django应用程序已设置为设置CSRF Cookie。Cookie中的CSRF令牌随后用于对API的请求(因此,该API作为同一Django项目的一部分运行)。
请注意,从Django角度来看,几乎与AngularJS应用程序相关的所有文件都是静态文件。Django应用程序仅需要提供index.html即可设置cookie。
在此应用程序的settings.py中(再次是Django项目settings.py的扩展),设置CSRF_COOKIE_DOMAIN,以便子域也可以使用它们:
CSRF_COOKIE_DOMAIN =“ .mydomain.com”
在views.py中,我只需要渲染一次AngularJS index.html文件,再次使用guarantee_csrf_cookie装饰器:
from django.shortcuts import renderfrom django.views.decorators.csrf import ensure_csrf_cookie# Create your views here.@ensure_csrf_cookiedef index(request): return render(request, ''index.html'')
使用AngularJS向API发送请求 -在AngularJS应用配置中,设置以下$ httpProvider默认值:
$httpProvider.defaults.xsrfCookieName = ''csrftoken'';$httpProvider.defaults.xsrfHeaderName = ''X-CSRFToken'';$httpProvider.defaults.withCredentials = true;
同样,请注意withCredentials,这可确保在请求中使用CSRF Cookie。
下面我展示了如何使用AngularJS $ http服务和JQuery向api发出请求:
$http.post("http://api.mydomain.com/myresource", { field1 : ..., ... fieldN : ...}, { headers : { "x-csrftoken" : $cookies.csrftoken }});
另请参见ngCookies模块。
使用JQuery(1.11.0):
$.ajax("http://api.mydomain.com/myresource", { type: ''POST'', dataType : ''json'', beforeSend : function(jqXHR, settings) { jqXHR.setRequestHeader("x-csrftoken", get_the_csrf_token_from_cookie()); }, cache : false, contentType : "application/json; charset=UTF-8", data : JSON.stringify({ field1 : ..., ... fieldN : ... }), xhrFields: { withCredentials: true }});
我希望这有帮助!!
AngularJS + Django Rest Framework + CORS(客户端未显示CSRF Cookie)
我正在使用AngularJS和Django Rest Framework + Django CORS Headers开发1页应用程序。
我的问题是,当我联系后端时,“ csrftoken” cookie永远不会显示在浏览器中。
例如:我正在使用帖子进行登录。我正确地获得了“ sessionid” cookie,但是“
csrftoken”却没有显示,因此我无法从客户端进行适当的发布,因为由于缺少csrf令牌而被拒绝了。
- 我已经分析了来自API的响应标头,而csrftoken却不是。
- 我直接在其余的API浏览器中查看,并在那显示很好。
- 只是指出,我可以做我的第一个POST登录,因为Django Rest Framework仅对经过身份验证的用户强制CSRF。如果我尝试重新登录,它将因为显示“ sessionid” -cookie而失败。
- 我对绕过CSRF的保护并不感兴趣,就像关于stackoverflow的一些帖子所建议的那样。
来自前端/后端的一些代码片段。这些都是未完成的代码段,因此请不要挂在写得不好的代码上。
后端API LoginView
class LoginView(APIView):
renderer_classes = (JSONPRenderer,JSONRenderer)
def post(self,request,format=None):
serializer = LoginSerializer(data=request.DATA)
if serializer.is_valid():
userAuth = authenticate(username=serializer.data['username'],password=serializer.data['password'])
if userAuth:
if userAuth.is_active:
login(request,userAuth)
loggedInUser = AuthUserProfile.objects.get(pk=1)
serializer = UserProfileSerializer(loggedInUser)
user = [serializer.data,{'isLogged': True}]
else:
user = {'isLogged': False}
return Response(user,status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
客户端AngularJS登录控制器
.controller('LoginCtrl',['$scope','$http','uService','$rootScope',function(scope,$http,User,rootScope) {
scope.login = function() {
var config = {
method: 'POST',withCredentials: true,url: rootScope.apiURL+'/user/login/',data : scope.loginForm
};
$http(config)
.success(function(data,status,headers,config) {
if (status == 200) {
console.log(data[0]); //Test code
// succefull login
User.isLogged = true;
User.username = data.username;
}
else {
console.log(data); //Test code
User.isLogged = false;
User.username = '';
}
})
.error(function(data,config) {
console.log('Testing console error');
User.isLogged = false;
User.username = '';
});
};
}]);
任何有好的技巧/想法/例子的人吗?
AngularJS iframe跨域打开内容时报错误的解决办法_AngularJS
打开不同域的内容时报下面的错误:
Blocked loading resource from url not allowed by $sceDelegate policy
解决方案:
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
''self'',
// Allow loading from our assets domain. Notice the difference between * and **.
''http://media.w3.org/**'']);
});
很简单的方法就解决了angularjs跨域使用iframe的问题,希望大家能够喜欢
今天的关于Play Framework 2.1-AngularJS路由-最佳解决方案?和angularjs路由原理的分享已经结束,谢谢您的关注,如果想了解更多关于Angular2 (One framework 概要)、AngularJS + Django Rest Framework + CORS(CSRF Cookie未显示在客户端中)、AngularJS + Django Rest Framework + CORS(客户端未显示CSRF Cookie)、AngularJS iframe跨域打开内容时报错误的解决办法_AngularJS的相关知识,请在本站进行查询。
本文标签: