【问题标题】:ngResource PUT returns bad request due to $promise and $resolved in the JSON object由于 JSON 对象中的 $promise 和 $resolved ,ngResource PUT 返回错误请求
【发布时间】: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


【解决方案1】:

根据docs,您没有完全正确地使用更新操作。

所以你的 updateStock 方法应该是:

$scope.updateStock=function(stock) {
    Stock.update({id: stock.id}, stock);

    Stock.update({id: $scope.stock.id}, $scope.stock);   //not sure why you have 2 calls here

    $state.go('stocks');
};

【讨论】:

  • 嗨。我有两个电话只是因为我尝试了两种不同的方式。不幸的是,在更新方法中添加 id 并没有改变任何东西。功能保持不变,但我不断收到错误请求,因为它们 $promise 和 $resolve 元素仍在 JSON 上。
【解决方案2】:

只要看看工厂定义和它与我的不同,你应该将工厂定义的第二个参数更改为数组,如下所示:

.factory('Stock',[$resource, function($resource){
    return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
        { id: '@id' },{
            update: { method: 'PUT' },
            show: { method: 'GET' }
    }); 
}]);

不确定这是否是问题所在,但这至少与 Angular 文档对依赖注入的定义有很大不同:https://docs.angularjs.org/guide/di

如果没有,你能否在GET返回数据后打印出$scope.stock的内容?

【讨论】:

  • 很抱歉,一直很忙,回复慢。如果我这样运行它,我会收到一条错误消息:“Uncaught ReferenceError: $resource is not defined”——但是,根据您链接的文档,它似乎应该像那样工作。今晚晚些时候我会进一步调查。感谢您的回复。
【解决方案3】:

我知道这个问题已经很老了,但我偶然发现了同样的问题,发现了这个 SO question 以及这个问题: http://www.scriptscoop2.com/t/fddc3f0a1f6f/angularjs-using-ngresource-for-crud-adds-extra-key-value-when-using-save.html

有 1 个答案解释了问题是由于 CORS(跨来源)引起的。这意味着您的服务器端需要允许它。如果您使用的是 Spring MVC,则在控制器请求映射中添加 org.springframework.web.bind.annotation.CrossOrigin 注释就足够了:

@CrossOrigin
@RequestMapping(value = "/product/{id}", method = RequestMethod.POST)
@ResponseBody
public void editProduct(@PathVariable("id") final long id, @RequestBody final ProductDto productDto) {
    // your code
}

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2019-07-28
    • 2016-02-25
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2015-07-05
    相关资源
    最近更新 更多