简体   繁体   中英

Angular $http bad request

Below I've got a function that should make a post to the server.

  var updateApplicationMetadata = function(appId, editorVersion, previewPubFile){
        var deferred = $q.defer();
        var result = $http({
            method: 'post',
            url: '../resource/applications/'+appId,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: {
                editorVersion: editorVersion,
                previewPubFile: previewPubFile
            }
        });
        result.then(function(data){
            deferred.result(data);
            console.log('from services: ');
            console.log(data);
        });
        return deferred.promise;

        };

I call this function like:

$scope.update = function(){
        MessageBus.emitMsg('notification','Application updates successful.');
        console.log('from update: ');
        console.log($scope.application.appId);
        console.log($scope.application.editorVersion);
        console.log($scope.application.previewPubFile);
        DataContext.updateApplicationMetaData($scope.application.appId,$scope.application.editorVersion ,$scope.application.previewPubFile);
    };

All of the values sent to the updateApplicationMetaData are valid. I can use the rest client POST man and I can make the post work. When I do it in angular, however, I get a bad request. The URL and header content type are right, but I'm not sure about the data object. It must be malformed. What am I missing here?

You've got an error in your code. You have:

deferred.result(data);

and it should be:

deferred.resolve(data);

for it to work. Also, you need to pass 'application/json' as your accepts type for your data to work.

Assuming you are using the $q service from https://docs.angularjs.org/api/ng/service/ $q I don't see a result method. Perhaps change:

deferred.result(data);

To

deferred.resolve(data);

consider using ngResource for rest style json requests

Angular resource docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM