AngularJS:无法使用$ resource发送PUT请求

时间:2014-11-04 09:36:35

标签: angularjs http resources put ngresource

这是我的第一个问题,所以不要把我烧死。

我有一个API,我正在使用$ resource发送GET,POST,PUT,DELETE请求。我设法做了一个他们应该做的GET和POST请求,但每当我尝试发送PUT请求时,我都会收到404错误并发送一个OPTIONS方法。

基本上,我的PUT请求应该使用与POST相同的参数发送。当我通过Postman扩展发送看似相同的请求时,它工作正常。我只是不知道如何通过$ resource复制它。

带有问题的plunker:http://plnkr.co/edit/gJV4otD0XGKoQWOq3PdK(顺便说一下,关于plunkr比在粘贴的代码上要清楚得多)

services.js

angular.module('starter.services',['ngResource']).factory('RESTCalls', function ($resource) {
return $resource('http://api.artistappz.com/api/v1/news/:urlkey/:id/x-app-id/3865f620590f40d493ec8d900b4c24d3/', null, {
    update: {
        method:'PUT'
    },
    save: {
        method:'POST',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }
});

});

controllers.js

angular.module('starter.controllers',[]).controller('HomeController', ['$scope','RESTCalls', function ($scope, RESTCalls) {
$scope.RESTGet = function() {
    RESTCalls.get(function (response) {
        console.log(response);
    });
};

$scope.RESTPost = function() {
    RESTCalls.save('user_id=76A5FC91E4684FA1ACB2FDA645FD5B2C&title=dejan seme ti jebem krvavo&body=dejan&url=dejanurl',function(response) {
        console.log('SUCCESS:');
        console.log(response);
    },function (responseerr) {
        console.log('ERROR:');
        console.log(responseerr);
    });
};

$scope.RESTPut = function() {           
    ///item/84173EF7D6FD4469B411057C72F53DE2
    RESTCalls.get({urlkey:'item',id:'84173EF7D6FD4469B411057C72F53DE2'},function (response) {
        var tempobject = response.data.news['84173EF7D6FD4469B411057C72F53DE2'];
        tempobject.user_id = '76A5FC91E4684FA1ACB2FDA645FD5B2C';

        RESTCalls.update({urlkey:'item',id:'84173EF7D6FD4469B411057C72F53DE2'},tempobject);
    });
};}]);

邮递员PUT请求http://i.stack.imgur.com/zLMUA.jpg

2 个答案:

答案 0 :(得分:1)

这是关于'HTTP访问控制'。因为您向不同的域服务器请求资源。您可以执行GET和POST请求,但“PUT”是不同的。

浏览器端将首先发送“OPTIONS”请求。然后,在服务器“批准”后,使用实际的HTTP请求方法发送实际请求。

如果您检查了plunker中的网络请求,您会注意到它是'OPTIONS'请求而不是'PUT'。

Here is MDN document for OPTIONS request.

Here is a relative issue.

答案 1 :(得分:1)

To resolve this problem you can customize $resouce method in you service:

Consider the following example:

Service:

angular.module('myApp')
.factory('ProductService', ['$resource',
    function ($resource) {
        return $resource('/products', {}, {
            query: { method: "GET", isArray: true },
            create: { method: "POST"},
            get: { method: "GET"},
            remove: { method: "DELETE"},
            update: { method: "PUT"}
        });

    }]);

Controller :

// Update a product with PUT method
$scope.updateProduct = function() {
    ProductService.update({id: 1234,color:blue}, function(data) {
        // do something which you want with response
   });
};

For more detail please refer link.