【发布时间】:2015-02-06 12:44:58
【问题描述】:
在过去的几个小时里,我一直在努力解决这个问题,每个教程都指向我已经实施但不起作用的解决方案。
基本上我的 PUT 请求返回一个错误:
PUT http://localhost:8083/stockapi/rest/stocks/5485cba248673a0dd82bb86f 400 (Bad Request)
当我拦截请求时,我看到它包含一个 $promise 和 $resolved 数据元素:
> {"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXX","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
这是有道理的,因为我使用的是 ngResource 对象——但每个教程都表明以下代码应该能够处理它,但事实并非如此。
注意/编辑:如果我通过外部程序(例如 Postman REST 客户端)放置没有“$promise”和“$resolved”元素的 JSON 对象,那么它可以正常工作。
工厂:
.factory('Stock',function($resource){ return $resource('http://localhost:8083/stockapi/rest/stocks/:id', { id: '@id' },{ update: { method: 'PUT' }, show: { method: 'GET' } }); });
控制器(注意:做了 4 次更新,但没有一个起作用,4 次相同的错误请求):
.controller('StockEditController',function($scope,$log,$http,$state,$stateParams,Stock){
$scope.stock = Stock.get({id:$stateParams.id}); $scope.updateStock=function(stock) { Stock.update(stock); stock.$update(); Stock.update($scope.stock); $scope.stock.$update(); $state.go('stocks'); };});
我现在真的不知道如何以正确的方式使用 ngResource 对象,以便我可以使用它来放置/发布到我的网络服务。有什么想法吗?
谢谢!
编辑: Chrome 网络输出:
响应头
Remote Address:[::1]:8080
Request URL:http://localhost:8080/stockapi/rest/stocks/5485cba248673a0dd82bb86f
Request Method:PUT
Status Code:400 Bad Request
Request Headersview parsed
PUT /stockapi/rest/stocks/5485cba248673a0dd82bb86f HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 355
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/stockapi/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Request Payloadview parsed
{"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXXYYY","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
Response Headersview parsed
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Date: Tue, 09 Dec 2014 06:36:24 GMT
Connection: close
【问题讨论】:
-
对我来说,似乎服务器控制器未配置为接受 PUT 请求(也许它改为接受 POST)。您能否从 Chrome 控制台(网络选项卡)检查并复制和粘贴日志以显示实际发送的网络数据?
-
服务器接受 PUT 请求。当我从 JSON 对象中删除 $promise 和 $resolved 元素并使用 REST 客户端(例如 PostMan Chrome Extension)时,我可以毫无问题地放置(=更新)对象。还将查看 Chrome 控制台网络选项卡。
-
好的,那么请向我们展示您的客户端向服务器发送的内容(网络选项卡)。我敢打赌答案/线索就在那里。
-
现在添加到主帖中。感谢您的帮助。
-
您可以在请求负载上点击“查看源代码”以便我们查看整个内容吗?
标签: javascript json angularjs ngresource