$http.jsonp - unexpected token '<' - javascript

I'm able to get a response from the request but the .then() part of my code doesn't fire. What am I doing wrong?
window.distance24Result = function(data){ alert(data.distance); };
$http.jsonp("http://www.distance24.org/route.jsonp?stops="+city+"|"+country,{data:'jsonp',
jsonpCallbackParam: 'distance24Result'
})
.then(function(data){console.log(data);});

If you have a look at the docs, you'll have to pass jsonp as the jsonpCallbackParam so that Angular uses the correct request url. It's the name of the GET parameter, not the name of the callback function. Also, the path is route.json not route.jsonp.
$http.jsonp("http://www.distance24.org/route.json?stops="+city+"|"+country, {
jsonpCallbackParam: 'jsonp'
}).then(function(data) {
console.log(data);
alert(data.distance);
});
Alternatively, you can also use
$http.jsonp("http://www.distance24.org/route.json", {
params: {stops: city+"|"+country},
jsonpCallbackParam: 'jsonp'
})
Before Angular v1.6, there was no jsonpCallbackParam config value. Instead you'd use
$http.jsonp("http://www.distance24.org/route.json?jsonp=JSON_CALLBACK&stops="+city+"|"+country)
or
$http.jsonp("http://www.distance24.org/route.json", {params: {
"stops": city+"|"+country,
"jsonp": "JSON_CALLBACK"
}})

Related

angularJS: http request configuration url must be a string

I have a function that takes an input from the front-end, and then concatinates that input into an URL that I want to get from wikipedia. Since I had problems with CORS, I implemented my $http.get as JSONP, and now I get the following error:
angular.js:13236 Error: [$http:badreq] Http request configuration url
must be a string. Received:
{"method":"JSONP","url":"https://en.wikipedia.org/w/api.php?action=query&format=json&uselang=user&prop=extracts%7Cpageimages&titles=Maya+Angelou&piprop=name%7Coriginal"}
The thing is, that his error shows the concatinated url as a string?
Can anybody point out what I'm doing wrong?
This is the function I am calling:
//function to get author info from wikipedia
$scope.getAuthorInfo = function(author) {
//remove whitespace from author
author = author.replace(/\s/g, '+');
//concat the get URL
var url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&uselang=user&prop=extracts%7Cpageimages&titles=' +
author + '&piprop=name%7Coriginal';
//get author info from wikipedia
$http.get({
method: 'JSONP',
url: url
})
.then(function successCallback(response) {
$scope.author = response.data;
//for every result from wikipedia, trust the extract as html
for (var x in $scope.author.query.pages) {
$scope.author.query.pages[x].extract = $sce.trustAsHtml($scope.author.query.pages[x].extract);
}
}, function errorCallback(response) {
console.log(response);
});
};
If you need additional information, please let me know.
$http({
method: 'JSONP',
url: url
}).then(function successCallback(response) {
// ok
}, function errorCallback(response) {
// ko
});
$http.get is a shortcut method for $http({ method: 'GET' }), and expects the URL as the first parameter.
As you're using JSONP, you could also use the $http.jsonp shortcut:
$http.jsonp(url).then(function successCallback(response) {
// ok
}, function errorCallback(response) {
// ko
});

Get object by id using $resource

I am dealing with a little issue, and need some help.
I have an API setup, works just fine.
Now I want to get a single object using its ID. I have tried using $http, but could't get it to work. So I switched back to $resource. Here is what I have in my service file.
getPlatesInSelectedContainer: function() {
return $resource('/api/v1/platesincontainer/:id', {id: "#id" },{
get: { cache: true, method: 'GET' }
});
},
And in controller I am reaching to function doing so.
CleaningPlatesFactory.getPlatesInSelectedContainer({id : 1}, function(data){
$scope.plates = data;
console.log(data);
})
But this is not returning any results. What I am doing wrong?
UPDATE
Earlier I have tried $http but getting this.
I would still get $http to work. It's as simple as this:
getPlatesInSelectedContainer: function(data) {
return $http.get('/api/v1/platesincontainer/' + data.id);
}
You need to accept the data object in your service function.
Inside the service:
getPlatesInSelectedContainer: function(data) {
return $resource('/api/v1/platesincontainer/:id', {id: data.id },{
get: { cache: true, method: 'GET' }
});
}
Then call it like this:
getPlatesInSelectedContainer({ id: 123 })

How to get request url in an angularjs $http request

I have this request:
$http({
method: 'get',
url: '/api/items/',
params: {a: 1, b: 2, c: 3}
}).success(function (response) {
console.log(response);
}).error(function (err) {
console.log(err);
});
Is there a way, to fetch the url it used to make the request after the request has been made(in the callback or otherwise)?
I would want the output:
http://www.example.org/api/items?a=1&b=2&c=3
Here the same thing is done with jquery.
The success handler gets 4 parameters passed into it:
$http
.get({ url: '/someUrl', params: { q: 3 } })
.success(function(data, status, headers, config) {});
The fourth parameter config has the following properties:
{
method: "GET",
url: {
url: '/someUrl',
params: {
q: 3
}
}
}
You can use window.location.origin to get the base url and build a simple function to concat it all together.
This function should yield the expected response:
var baseUrl = window.location.origin;
var query = [];
Object.keys(config.url.params || {}).forEach(function (key) {
var val = config.url.params[key];
query.push([key, val].join('=')); // maybe url encode
});
var queryStr = query.join('&');
var fullPath = baseUrl + config.url.url + '?' + queryStr;
Unfortunately, this function will only work as long as the parameters are passed in the format described above. If you pass them in a different format, you'll have to modify this function a bit. You can use this as a playground.
Afaik, there is no simpler way. At least a feature request exists.
See the docs of $http for reference
This config parameter of the callback has the url as a property:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
console.log(config.url);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Based on: https://docs.angularjs.org/api/ng/service/$http
You can use http request Interceptor.
Configure the Interceptor in config function using $httpProvider
Whrein for request Interceptor you can able to see the URL and params that you passed with URL prior to making the request
try just looking at the XHR Request urls in your browser dev tools

AngularJS $http request object for another request

Sorry for the confusing title, basically I have a json file that looks like this that points to other locations:
{
"link": [
{
"href": "some-external-resource",
"title": "services-path"
}
]
}
My real problem is getting the href of the object to not load asynchronously into the Angular service. The following is my request to the above json file:
var servicesPath = $http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
return $filter('filter')(data.link, {title: "services-path"})[0].href;
});
console.log(servicesPath);
I know what is being returned is what I want, but the console log returns the standard "then, catch, finally, success, error" object functions, meaning the data isn't there when I need it. How can I manipulate my request so the variable contains the information?
Since you have an async call, the value would be returned when the call is finished (successfully)
$http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
console.log('response data', data);
var theHref = $filter('filter')(data.link, {title: "services-path"})[0].href;
console.log('theHref', theHref); // value shows here
}).error(function(errorResp){
console.log('error');
});

Migrating from http to ngResource Angular

It's been 3months since I've used angular and I'm loving it. Finished an app using it and now I'm on a code refactoring or improving my code for better practice. I have an Api service.js that used $http and I want to migrate it to using $resource :)
I have here a sample of my api code using $http:
Service.js
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
},
#Controller.js
Api.authenticatePlayer(postData).then(function (result){
//success
}, function(result) {
//error also this will catch error 400, 401, and 500
});
The above code are working and now here is my first attempt on using $resource:
authenticate: function() {
return $resource(api + "auth/:usertype",
{
typeOfUser : "#usertype" //types can be player, anonymous, admin
},
{
post : { method : "POST" }
}
);
}
#Controller
var postData = {
email : scope.main.email,
password : scope.main.password
};
var loginUser = new Api(postData);
loginUser.$post(); //error T__T
That just how far I get, don't know how to pass a data to my api using $resource from my controller. That just one part of my api call, there's still a bunch of it but for now this will do. :D.
Any help is greatly appreciated.
Thanks
You could try this:
API
authenticate: function(){
return $resource(api+"auth/:usertype",{},post:{method:"POST"});
}
Note: :usertype in URL means that the value of usertype property which you passed into postData will replace the part of URL
Controller
var postData = {email:scope.main.email,password:scope.main.password};
API.authenticate().post({usertype:'player'},postData,function(response){
console.log(response);
});
Or you could fetch response like this:
var response = API.authenticate().post({usertype:'player'},postData);
Hope this is helpful.

Categories