【问题标题】:Restangular.remove() Method DELETE is not allowed by Access-Control-Allow-MethodsAccess-Control-Allow-Methods 不允许 Restangular.remove() 方法 DELETE
【发布时间】:2016-06-24 15:30:50
【问题描述】:

我正在尝试使用 Restangular 实现 DELETE 方法,但它一直给出错误 Method DELETE is not allowed by Access-Control-Allow-Methods。

已经看了很多,但还没有找到解决方案。请求与 POST MAN 无缝协作

var users = Restangular.all("users", userId);
                   return users.remove()
                .then(function (response) {
                    return response;
                });

通过上述请求方法作为 OPTIONS 发送,我认为它应该是 DELETE

【问题讨论】:

    标签: angularjs restangular


    【解决方案1】:

    我也在做某事。这是一个解决方案:

    你必须在你的 api web.config 文件中更新

    <clear />
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="OPTIONS,GET,POST,PUT,DELETE" />
    

    ApiController

    [HttpDelete]
    public string Delete() 
    { 
        return "u call delete"; 
    } 
    
    public HttpResponseMessage Options() { 
        var response = new HttpResponseMessage(); 
        response.StatusCode = HttpStatusCode.OK; 
        return response;
    }
    

    在 Angular 中:

    home.post().then(function (data) {
        console.log(data);
    });
    
    home.remove().then(function (data) {
        console.log(data);
    });
    

    输出...

    > u call delete
    

    希望对你有帮助:)

    【讨论】:

      【解决方案2】:

      我会为我的控制器发布我的代码,希望对你有所帮助 我将此控制器与 angularjs 和 django rest 框架一起使用。在 CategorySerializer 我返回 pk 和名称

      类别序列化器:

      class CategorySerializer(serializers.HyperlinkedModelSerializer):
          owner = serializers.ReadOnlyField(source='owner.username')
          class Meta:
              model = Category
              fields = ('pk','name', 'owner','created')
      

      在我的 cotroller.js 文件中,我有以下代码来添加类别和删除类别:

      appcontroller.controller('Route1Ctrl', function Route1Ctrl($scope,Restangular) {
        $scope.test = 'hello world !!!'
        $scope.name = '' 
        $scope.delete = function(pk) {
           Restangular.one('categories/',pk).remove().then(function() {
             var index = $scope.categories.indexOf(pk);
             if (index > -1) $scope.categories.splice(index, 1);
           });
        };
        Restangular.all('categories/').getList({}).then(function(data) {
         $scope.categories = data;
        });
        $scope.addCategory = function() {
          categories.post({'name':$scope.name})
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2013-12-14
        • 1970-01-01
        • 1970-01-01
        • 2017-06-09
        • 2017-01-11
        • 2017-04-18
        • 2013-12-07
        • 2017-07-02
        • 2019-09-29
        相关资源
        最近更新 更多