POST请求给了我一个400 Bad Request

时间:2015-03-27 04:02:59

标签: angularjs angular-resource

我在项目中使用angularjs。每当使用AttachmentsFactory发出POST请求时,我收到400个错误请求。所有其他工厂的POST功能都正常工作。这是 控制器功能 `

$scope.updateAttachment = function(attachment){
        console.log(JSON.stringify(attachment));
        var response = AttachmentsFactory.update(attachment); //**here's the problem**
        response.$promise.then(function(data){
            attachment.edit = false;
        })
        /*$http.post("/rest/attachments", attachment).success(function(data){
            //Callback function here.
            //"data" is the response from the server.
        });*/   
    }

` 和工厂 AttachmentsFactory

services.factory('AttachmentsFactory', function ($resource) {
   return $resource('/rest/:eventId/attachments/:fileId', {}, {
       query: { method: 'GET', isArray: true },
       remove: {method: 'DELETE'},
       update: {method: 'POST', headers:{'Content-Type':'application/json'}}
   })
});

请求未到达服务器。作为参数传递的对象是有效的: {"name":"ccccc", "description":"cccc cccc cccc cccc cccc cccc cccc", "fileId":"55144430d18567d9335a94c7", "thumbNailId":null, "extenstion":"jpg", "visibleToPublic":false, "edit":true, "$$hashKey":"object:565" }

接收其余部分的服务器功能如下

@BodyParser.Of(BodyParser.Json.class)
public Result updateEventAttachment(String eventId) {
    try {
        logger.warn("HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE ");
        JsonNode json = request().body().asJson();
        Attachment attachment = Json.fromJson(json, Attachment.class);
        logger.debug("Update Request received eventId ={}, fileid{}", eventId, attachment.getFileId());
        Event event = eventService.getEvent(eventId);
        Set<Attachment> attachments = event.getAttachments();
        logger.debug(" Size of attachments = {}", attachments.size());
        attachments.remove(attachment);
        attachments.add(attachment);
        eventService.updateEvent(event);
    } catch (Exception e) {
        logger.warn(" method = deleteEventAttachment exception={}",
                e.toString());
        e.printStackTrace();
    }
    return ok();
}

我将字段headers:{'Content-Type':'application/json'}添加到POST方法,它没有帮助。我也尝试在$ resource上使用$ http。还是一样。尝试用PUT替换POST,仍然是一样的。 AttachmentsFactory的GET和DELETE函数正常工作。 任何人都可以帮我弄清楚我做错了什么? 已经坚持了一天以上。

1 个答案:

答案 0 :(得分:0)

我忘了在服务器期待的前端控制器中添加一个参数。修改控制器如下解决问题。

$scope.updateAttachment = function(attachment){
    console.log(JSON.stringify(attachment));
    var response = AttachmentsFactory.update({'eventId':$routeParams.id},attachment);
    response.$promise.then(function(data){
        attachment.edit = false;
    })
}
相关问题