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

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.

Related

I am uploading the image file in Angular Js to call the java api but my form data is not hitting the api

controller:
$scope.fileToUpload = function(input) {
if (input.files && input.files[0]) {
CommonService.uploadContactImage.upload({
fileName : input.files[0].name
}, input.files[0], function(data) {
});
}
}
Service:
uploadContactImage:function(input){
console.log("game image");
var req = $http({method: 'POST', url: options.api.base_url + '/gameimageupload/',
dataType: 'json', headers: {'Content-Type': undefined}})
.success(function (data)
{
console.log("data" + data);
return data;
});
If you take a good look at your code you will see that there are quite a few things wrong with it. For example, you have defined in your service an uploadContactImage function which takes a single Javascript object as argument (input), while in your controller you attempt to call CommonService.uploadContactImage.upload(...) instead of CommonService.uploadContactImage(...). Additionally, even if the uploadContactImage function was called correctly it doesn't actually do anything with its argument, ie. the input object is never used in the function body.
These issues aside you cannot submit a file to the server just by adding it to the body of a POST request the way you (seem to be) trying to do. Without going into too much detail here, in order to upload a file from the browser a request with content type multipart/form-data needs to be submitted, which will contain your file as well as the necessary HTTP headers for the server to identify it and parse it correctly. I suppose you could try and construct this request yourself, however it's not a task for the faint-hearted. What I would suggest instead is to use one of the many file upload modules available for Angular.js. A Google search will give you quite a few modules that you can check out to see which better fits your needs.

AngularJS continues to perform preflight request even without application/json content type

At this point I am at a complete loss. I have searched the SO and the documentation and it says that Angular's $http will not perform an OPTION request if you put anything but content-type: application/json
I have the code below:
$scope.login = function(){
authFactory.login($scope.username, $scope.password).success(function(){
alert("here");
}).error(function(){
alert("ERROR");
});
app.factory('authFactory', ['$http', function ($http) {
var factory = {};
factory.login = function (username, password) {
var data = new Object();
data.username = username;
data.password = password;
return $http({
method: 'POST',
url: wsURL + 'login',
data: data,
headers: {
'Content-Type': 'x-www-form-urlencoded'
}});
}
return factory;
}]);
I keep getting an OPTIONS request and I cannot do anything about it.
My server is an embedded Jetty who is lacking an web.xml so I had to go at great lengths to configure it. At some point I seemed to work and not send the options request but out of the blue (without changing anything it stopped again).
Any help?
After all, SoluableNonagon was right that because I was sending a custom header I could not avoid the preflight request to Jetty. However, after searching for a way to make it work.
I am posting here for helping anyone else with similar needs.
The way to make this work with Jetty is to configure the CrossOriginFilter appropriately so as to not chain the request to your application if you do not want this (as was my case). The way to do this is below.
FilterHolder holder = new FilterHolder(new CrossOriginFilter());
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER, "GET,POST,HEAD,OPTIONS");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "*");
holder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_EXPOSE_HEADERS_HEADER, "true");
holder.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "X-AUTH-TOKEN");
Notice the statements responsible for allowing the header to pass and stop chaining it to the application are holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "*"); and holder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false");.
The last two statements in the codeblock above are responsible for allowing you to retrieve the token from the custom header. Not entirely relevant to the question but will definitely be needed.

Angular wait for a $http call to execute the next function

I had been searching for this same issue here, I found something but all that seems to not be working for me. Let me describe my scenario:
I am adding some features to a Web app done by myself, that Web app is used to manage the developing of the webpage of some customers. Each customer has a webpage and for each customer there are a list of proposals webpages and who of the designers did that proposal, fine.
The list of the developers and be able to see who did what is the new thing in the Web app and the reason of my question, so, the problem is:
Once the web app loads I get the list of developers from the DB and a list of all the customers that have a webpage. So, the next thing the web app does is auto-select the first customer of the list and show its proposals in another list. To do that, the list of the developers is needed, but as it hasnt been still loaded I get the:
Cannot read property '0' of undefined
When I want to iterate over the $scope.developers object
What I do to get the developers is a $http call like this:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
$scope.developers = data;
});
I know $http performs async calls, but i need something that waits until the $scope.developers has the data loaded.
The problem comes when I need to use the data supposedly stored in $scope.developers but obvously its not. I tried to call the function that uses the $scope.developers inside the .success function but the same happens.
I tried to use the solution in this thread but I get the same error.
How to wait till the response comes from the $http request, in angularjs?
Any help ?? If something in my question is not clear I will try to explain it better.
Please just define $scope.developers as empty array before $http call ie
app.controller("someCtrl", function($scope, $http) {
$scope.developers = [];
//....
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
$scope.developers = data;
});
//..
});

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

Angular $httpProvider transformResponse data contains local HTML DOM elements?

When I instantiate the following code in an AngularJS app, I get weird data in the transformResponse function (bottom of code). I'm not calling the $resource function from any controller, just loading the script in a browser. The data variable (see code) contains the HTML of the current partial, when loading the app.
This seems odd. Is this the way it's supposed to be?
var buddyServices = angular
.module('buddyServices', ['ng','ngResource'])
.factory('Buddy',
function ($resource) { console.log('resource');
return $resource('http://webservice.buddyplatform.com/v1/:service',
{service:'', BuddyApplicationName: 'xxx',
BuddyApplicationPassword: 'yyy'}
);
}
)
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.transformResponse = function(data) {
console.log(data);
return 'TEST: '+data;
};
});
=== EDIT ===
It just daunted on me: $httpProvider handles all http requests, so a page load is one of those. I'm guessing a bit now, but it seems probable. So, the question then becomes: Is there an "easy" way to constrain the data in the code above to only those requests performed by my service?
transformResponse takes another parameter headersGetter. You can use this to get the headers send with the response. Look for Content-Type header header. It should contain application/json

Resources