演示:http: //jsfiddle.net/rob_balfre/7QUUf/
您如何使用 $resource 发布数据(跨域)?
例如,此 curl 毫无问题地写入 API:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name": "Wobbly"}' http://192.168.91.20/api/food/
并且标头响应是:
HTTP/1.0 201 CREATED
Date: Thu, 25 Oct 2012 08:19:42 GMT
Server: WSGIServer/0.1 Python/2.6.1
Access-Control-Allow-Headers: Content-Type,*
Location: http://localhost/api/food/15/
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf-8
我完全被困在如何以同样的方式获得 POST 的角度。这是我的 $resource,值得注意的是 'get' 工作得很好:
angular.module('tastypieModule', ['ngResource']).
factory('FoodOptions', function($resource, $timeout) {
var FoodOptions = $resource('http://testurl/api/:type',
{type: 'food'},
{
get: {method: 'JSONP', params: {format: 'jsonp', callback:'JSON_CALLBACK'}},
update: {method: 'POST', headers: {'Content-Type': 'application/json'}}
}
);
return FoodOptions;
})
当我调用更新时它失败了,我看到这是控制台网络选项卡:
METHOD: OPTIONS
STATUS: (canceled) Load cancelled