Bob Horn
Bob Horn

Reputation: 34297

$.ajax call works, $http.get() does not (404, not found)

I'm trying to replace my $.ajax call with $http.get(). I get a 404 Not Found error when I try.

Here is the ajax call:

    //  ToDo: See if there is an $http.get equivalent. That way the callback doesn't have
    //        to be wrapped in $scope.apply().
    $.ajax({
        url: '/PrestoWeb/api/ping/responses/',
        type: 'POST',
        data: JSON.stringify(latestPingRequest),
        contentType: "application/json",
        success: function (responses) {
            // do stuff
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });

And this is the $http call:

    var config = {
        url: '/PrestoWeb/api/ping/responses/',
        method: 'POST',
        data: JSON.stringify(latestPingRequest),
        contentType: "application/json"
    };

    $http.get(config)
        .then(function (response) {
            // do stuff
        }, function (response) {
            alert(response);
    });

The ajax call works. The http call does not. The URL, type, and data are the exact same in both calls. What am I missing?

Upvotes: 0

Views: 357

Answers (1)

Dustin Hodges
Dustin Hodges

Reputation: 4195

It looks to me like the problem you are having is using $http.get instead of $http.post. The $http object has some helper methods for the common http verbs, e.g. $http.get, $http.post, $http.put which will set the method to the name of the shorthand. The helper method for post expects three parameters, a url, your data and a configuration object so your call would look like, $http.post('/PrestoWeb/api/ping/responses/', latestPingRequest, config)

In your case you specify method: 'POST' in your http configuration object but then use the $http.get method, which will make a get request instead of what you specified in your configuration object.

Because you specified the method in your configuration object, you could just use $http(config) and skip the helper methods entirely. I actually prefer doing things this way as your full request is defined in the configuration object and not the configuration object and method used. The helper methods also all have different signatures which is confusing. Easier just to stick to the $http(config) IMO

Upvotes: 2

Related Questions