Zorgatone
Zorgatone

Reputation: 4283

400 Bad Request only using AngularJs, works with jQuery

I am having troubles using AngularJs for a specific "PUT" Ajax request (RESTFul service).

The same piece of code works with jQuery and plain JavaScript.

$http({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        "Content-type": "text/plain",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: {
        Email: email,
        Uuid: login_response.uuid
    }
}).success(function(response) {
    console.log(response);
});


jQuery.ajax({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        "Content-type": "text/plain",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: {
        Email: email,
        Uuid: login_response.uuid
    }
}).done(function(response){
    console.log(response)
});

The server is responding with a JSON object, but the first code (AngularJs) seems to work a bit differently. Before I wasn't setting the Content-Type header and I was getting a CORS issue (worked with jQuery, but AngularJs was setting the content-type to "application/json" and was causing an error).

I got the first part fixed setting the content-type to text/plain, but now I'm getting a 400 Bad Request Error (only with AngularJs). I also tried to delete the transformRequest using an interceptor, but it didn't work.

Am I using AngularJs wrong? Because I'm thinking that, unlinke jQuery, it is doing extra "stuff" in the background, making some extra headers or not passing the data correctly.

Usually I get that error when I do not pass any data to the RESTful service.

I am learning AngularJs, so I'd rather use it instead of jQuery. Any help would be much appreciated.

Thanks a lot

Upvotes: 2

Views: 3067

Answers (1)

Zorgatone
Zorgatone

Reputation: 4283

I got it, jQuery was automatically serializing the data object to application/x-www-form-urlencoded, AngularJs wasn't...

Working Code:

$http({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        Accept: "*/*",
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: jQuery.param({
        Email: email,
        Uuid: login_response.uuid
    })
})

Anyway this doesn't look so well, but it's working at least.. Anybody knows a better way to get AngularJs to send serialized data as x-www-form-urlencoded?

Upvotes: 1

Related Questions