Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

Can't call Rest Api from $http.get

I'm trying to access a REST API which I'm working on. The client for this application is an AngularJS website.

When calling the REST API I get the following error

Http request configuration url must be a string or a $sce trusted object. Received: {"method":"GET","url":"http://localhost:51615/api/Call/2/{\"Request\":\"INIT\"}"...}}

The code I'm using is this:

var json = JSON.stringify({
        Request: 'INIT'
    }),
    req = {
        method: 'GET',
        url: 'http://localhost:51615/api/Call/2/' + json,
        headers: {
            'Content-Type': 'application/json'
        }
    }

console.log('req : ', req)

$sce.trustAsResourceUrl(req.url)
$http.get(req)
    .success(function (response) {
        console.log(response)
    })
    .error(function (error) {
        console.error(error)
    });

The errors tells me that the $http url must be a string, but as far as I can see it is. So what might be the problem?

Upvotes: 0

Views: 1101

Answers (1)

baao
baao

Reputation: 73211

req is clearly an object. Try req.url instead. You can pass your configuration object (req) as the second parameter, as the documentation explains.

$http.get(req.url /*String*/, req /*object*/).then()

Note that it is not needed to tell angular the request-method, it's already get in $http.get. So your code would work like this

var json = JSON.stringify({
    Request: 'INIT'
}),
config = {
    headers: {
        'Content-Type': 'application/json'
    }
},
url = 'http://localhost:51615/api/Call/2/' + json;

$http.get(url, config)
    .then(successCallback, errorCallback);

I'm also unsure if the application/json header in a get request that sends a string is what you want, but that's another story.


Another way would be not to use the shorthand for the request, in that case, you can pass the object you created (req) to $http():

$http(req)
    .then(s, e);

Upvotes: 1

Related Questions