Access the Real URL for JSONP request in AngularJS - angularjs

Here's the basic setup for a JSONP call using $http's JSONP function
var authenticatedUrl = authenticateUrl("http://example.com/getStuff&callback=JSON_CALLBACK");
return $http.jsonp(authenticatedUrl).then(function (response) {
...
}
The problem is, my HMAC authenticator is creating a hash based on the url with callback=JSON_CALLBACK, then by the time angular makes the actual request, the URL changes to have angular.callbacks._0 as the callback param, which makes my authentication hash invalid.
How do I access the real url that will be used for this JSONP request?
From my research, it appears that interceptors is the way to go with this, but I can't seem to find an object with the URL that has the angular.callbacks._0 callback.

If I understand correctly you are using something like Hawk - Single URI Authentication; this is you get a token that you have to attach to the url and the token is valid for that exact url.
The problem you have, it is not angular per-se but the way that every jsonp framework is supposed to work.
I will suggest forking JSONP to add this behavior or doing JSONP manually.
var i = 0;
function call_endpoint(callback) {
i++;
var url = "http://example.com/getStuff&callback=callback_" + i;
//append the token here, or call your endpoints to fetch the endpoint.
window["callback_" + i] = function (data) {
delete window["callback_" + i];
callback(data);
};
script = document.createElement('script');
script.src = url;
var target = document.getElementsByTagName('script')[0] || document.head;
target.parentNode.insertBefore(script, target);
}

Related

Postman - How do I loop a request in another request's test script?

I have a request that returns an array and I, thanks to StackOverflow, figured out how to make each object in the array its own environment variable. Now I want to make a request per variable in the same request as I instantiated the variable. Here is what I got:
var a = pm.response.json();
for (i = 0;i < a.sick_beats.length; i++){
pm.environment.unset("Beat_" + (i+1));
pm.environment.set("Beat_" + (i+1), a.sick_beats[i]);
pm.sendRequest("Publish Beat");
}
It sends the request "Publish Beat" but uses it as the URL instead of referencing the request.
I guess my question is how can I reference a request name instead of a URL, since the old way postman.setNextRequest("Request_Name"); doesn't work.
This pm.* function doesn't work in this way:
pm.sendRequest("Publish Beat")
Check out this blog from Postman explaining it more.
This is a basic extract from the snippets in the application. The first arg is the URL.
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
You can use pm.setNextRequest('request_name') to create a workflow but this will only work in the Collection Runner and not for single requests. You can add a collection of requests and chain these together using the {{Beat_1}} variable in the URL.
Alternatively, you could add something like this but it's very hacky and wouldn't ever send requests over and over again, like the collection runner would:
var some_value = pm.environment.get('Beat_whatever')
pm.sendRequest(`https://your-super-secret-site.com/${some_value}`, (err, response) => {
// This is just here so you can see the response
console.log(response.json())
})

JHipster : when to use $http and when to use $resource

I'm exploring how jhipster manipulates data. I have found $http.get() in getProfileInfo method in ProfileService Service whitch interacting restful api :
function getProfileInfo() {
if (!angular.isDefined(dataPromise)) {
dataPromise = $http.get('api/profile-info').then(function(result) {
if (result.data.activeProfiles) {
var response = {};
response.activeProfiles = result.data.activeProfiles;
response.ribbonEnv = result.data.ribbonEnv;
response.inProduction = result.data.activeProfiles.indexOf("prod") !== -1;
response.swaggerDisabled = result.data.activeProfiles.indexOf("no-swagger") !== -1;
return response;
}
});
}
return dataPromise;
}
and some where i have found $resouce() manipulating GET method. for example in BankAccount factory :
var resourceUrl = 'api/bank-accounts/:id';
I searched for when to use $http and when to use $resource and i found this :
AngularJS $http and $resource
why hipster is not following consistent way of interacting API and manipulating data!!?
so jhipster, when to use $http and when to use $resource in services??
We use $resource when requesting a RESTful endpoint, for example for an entity. $resource provides basic REST operations easily whereas $http is more specific.
For profile we only need to GET /profile-infos so it's useless to use $resource because we'll never need to call POST or DELETE on that URL.
$http will fetch you the entire page or complete set of data from a given URL whereas $resouce uses http but will help you to fetch a specific object or set of data.
$resource is fast and we use it when we need to increase the speed of our transaction.
$http is used when we are concerned with the time.

How to authenticate a HTTP request to an OrientDB function on AngularJS?

I have the following OrientDB function:
http://localhost:2480/function/Application/getPassFailCount/9:600
And it returns the following JSON result:
{"result":[{"#type":"d","#version":0,"pass":16.0,"fail":2.0,"#fieldTypes":"pass=d,fail=d"}]}
What I need to do is to get the values of "pass" and "fail" to use in my web page.
So far I have done this with AngularJS:
$http.get('http://localhost:2480/function/Application/getPassFailCount/9:600').
success(function(data) {
$scope.data = data.result;
// $scope.passCount = ;
// $scope.failCount = ;
});
Currently it gives the error "401 Unauthorized". How do I authenticate the request?
And if possible, can anyone give some tips on how to get the passCount and failCount from the JSON result returned?
The OrientDB HTTP API documentation states that you have to use HTTP Basic authentication for issuing commands. That means you have to include an Authorization header along with your request.
There are a few ways to achieve this, here is a simpler one. Use the configuration object parameter for $http.get to set the header on the request:
function base64(str) {
return btoa(unescape(encodeURIComponent(str)));
}
$http.get('http://...', {
headers: { 'Authorization': 'Basic ' + base64(user + ':' + password) }
}).success(...);
You should definitely move all your database logic to an Angular service, so you can keep this code in one place instead of polluting your controllers.
To make it even cleaner, you could look into $http interceptors and write a request interceptor that adds the header to every HTTP call.
Regarding the JSON question: you can see that the result object contains an array with a single element. Use indexing to get the actual record.
var result = data.result[0];
$scope.passCount = result.pass;
$scope.failCount = result.fail;
If you wrote a service as I mentioned, you could hide this implementation detail from your controller.
function getCount() {
return $http.get(...).then(function (data) {
var result = data.result[0];
// the caller will only see this simpler object
return { pass: result.pass, fail: result.fail };
});
}

Can I use $http to get a javascript for my web page?

I am using the following code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
Can someone advise me if it is possible to get a javascript with $http and show me how I can do it inside a function that returns a promise when it is completed. The reason I would like to use $http is that along with the request for the js I need to send a custom header for authorization.
Please note that this question is different from the one suggested as a duplicate in that I am also wanting to find out if I can get a javascript and add it to the page DOM in the same way as it was done with the .setRequestHeader. Thanks
Since $http is a implementation for XMLHttpRequest in Angular, you can of course make requests to get the contents of a JS file.
You can set additional headers with $http like this:
$http({
method: 'get',
url: 'some/js/file.js',
headers: {
"X-Custom-header": "foo"
}
}).then(function (data) {
// do something with the DOM here
});
So as you can see, you are actually able to do that.

How can I build a get request with url that contains parameters

I am trying to do a get request to recover data from the server using the following url:
url = /api/projects/:projectId/scenarios
How can I do that using $http.get in AdngularJS?.
you might want to take a look at Restangular, I like its notation more than standard angularjs $http or $resource.
Restangular.setBaseURL('/api/');
Restangular.one('projects', projectId).all('scenarios').getList().then(function(data) {
myVariable = data;
});
Restangular

Resources