通过URL发送参数的PUT请求

5
我有一个订单资源,看起来像这样。
.factory('Order', order)

order.$inject = ['$resource', "ApiEndpoint"];

function order($resource, ApiEndpoint) {
  return $resource(ApiEndpoint.url + 'orders.json', {}, {
    create: {method: 'POST', url: ApiEndpoint.url + 'orders.json'},
    update: {method: 'PUT'},
    edit: {method: 'GET', url: ApiEndpoint.url + 'orders/edit.json'},
    remove_item: {method: 'GET', url: ApiEndpoint.url + 'orders/remove_item.json'},
  });
}

当我执行以下代码Order.update

var params = {
  order: {
    line_items_attributes: {0: {quantity: 2, id: 1}}
  },
  order_id: 3
};

Order.update(params, function (resp, respHeaders) {
  console.log("response headers", respHeaders());
  console.log("change quantity resp", resp);
})

我也尝试了这个:

Order.update({}, params, function (resp, respHeaders) {
  console.log("response headers", respHeaders());
  console.log("change quantity resp", resp);
})

发送到服务器的参数最终会出现在URL中。例如,这是服务器收到的其中一个URL。

path="/api/mobile/orders.json?order=%7B%22line_items_attributes%22:%7B%220%22:%7B%22quantity%22:8,%22id%22:356265%7D%7D%7D"

需要注意的是,服务器接收到的方法是OPTIONS请求。服务器已经设置好处理这种请求。

既然我发送的是PUT请求,为什么$resource通过URL传递参数而不是作为负载的一部分呢?

2个回答

1

来自文档

非 GET 的 "class" 操作:Resource.action([参数], postData, [成功回调], [错误回调])

负载是第二个参数,因此请尝试使用以下代码

var params = {
  order: {
    line_items_attributes: {0: {quantity: 2, id: 1}}
  },
  order_id: 3
};

Order.update({}, params, function (resp, respHeaders) {
  console.log("response headers", respHeaders());
  console.log("change quantity resp", resp);
})

只需在update方法的第一个参数中添加一个空对象。

还要查看与自定义put请求相关的部分。


我尝试过这个,但参数仍然被加载到URL中。 - thank_you
调用OPTIONS应该由CORS引起,你的API端点是否与Angular应用程序位于不同的域上? - Giovanni Vinaccia
是的,没错。我相信在过去我们已经纠正了这个问题,因为我们以前正在进行POST请求,而POST请求不像PUT请求那样将参数传递到URL中。 - thank_you
问题不在于PUT方法,而是CORS,看一下这个codepen,如果你看到PUT调用,你会看到传递到请求体中的参数。 - Giovanni Vinaccia
谢谢。但我仍然不知道如何修复这个问题。 - thank_you

0

如果您正在更新订单,则应指定订单ID,以便服务知道要更新哪个订单

function order($resource, ApiEndpoint) {
  return $resource(ApiEndpoint.url + 'orders.json/:orderid', {}, {
    create: {method: 'POST', url: ApiEndpoint.url + 'orders.json'},
    update: {method: 'PUT',params : {orderid : '@order_id'},
    edit: {method: 'GET', url: ApiEndpoint.url + 'orders/edit.json'},
    remove_item: {method: 'GET', url: ApiEndpoint.url + 'orders/remove_item.json'},
  });
}

然后是你的调用

Order.update(params, function (resp, respHeaders) {
  console.log("response headers", respHeaders());
  console.log("change quantity resp", resp);
})

抱歉,但参数仍然通过URL传递。 - thank_you

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接