2014-03-27 68 views
3

我念叨Restangular到处都提到Restangular承诺和角度的作品聪明和模板在以下情况下更新这样的:Restangular失败,诺言和跨域请求

As Angular supports setting promises to scope variables as soon as we get the information from the server, it will be shown in our template

$scope.something = Restagular.one('something').get(); 

我试图做同样的事情,但Restangular是在服务中,因为我想保持我的控制器清洁。当我做我的REST API的角模板没有更新的请求,我收到此错误:

XMLHttpRequest cannot load http://localhost:3000/api/template/1 . The request was redirected to 'http://localhost:3000/api/template/1/' , which is disallowed for cross-origin requests that require preflight.

这里是我的代码: 在服务...

myAppServices.service('TemplateService', ['$http', '$cookies', '$cookieStore', Restangular', 
         function($http, $cookies, $cookieStore, Restangular) { 

    Restangular.setBaseUrl(constants.serverAddress); 

    var getTemplate = function(templateId) { 
     // Check the input 
     if (!isValidId(templateId)) 
      return; 

     return Restangular.one('api/template', templateId).get(); 
    }; 

    // Public getters 
    this.getTemplate = getTemplate; 
}]); 

在控制器..

$scope.currentCard = TemplateService.getTemplate(1); 

那么,在这种情况下,该问题 - 在客户端上或在服务器上。对于我的API,我使用的是django-rest-framework,但是当我使用所有模板(没有特定的ID)获取列表时,我没有问题。

我知道我可以尝试从服务和它的.then()返回一个承诺来设置我的范围变量,但在Restangular的官方回购中提到了这一点,我想使用它,因为代码保持清洁。

回答

2

您遇到的问题是因为Django会自动将没有斜杠的网址用斜杠重新定向到网址。这不是特定于框架的,因为我最近发现了it is an issue for ExtJS as well

由于您要求的网址api/templates/1没有结尾的斜杠并且API在api/templates/1/处服务,Django会自动将请求从一个位置重定向到另一个位置。通常这个问题是一个问题,你只能看到控制台中发生的重定向,没有人关心,但CORS要求你有的权限,这意味着它不能重定向。

您可以修复这两种不同的方式:在客户端或服务器端。


如果你想解决这个问题的客户端,并保持服务器需要斜线,你需要告诉restangular以斜线添加到末尾。 Restangular allows you to do this通过设置

RestangularProvider.setRequestSuffix('/'); 

在你的代码,它会告诉restangular总是添加结尾的斜线。


如果你想解决这个问题的服务器端,你将需要停止要求斜线你的API中。这具有令人不快的副作用不允许使用斜杠的任何请求,并且可能会破坏正在按预期工作的现有应用程序。 Django REST Framework allows you to do this on the router level通过在初始化路由器时设置trailing_slash=False

router = SimpleRouter(trailing_slash=False) 

这将告诉Django REST框架注册所有的URL没有结尾的斜杠。