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

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.

Related

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 };
});
}

AngularJS - Setting default http headers dynamically

To overcome csrf attack, I have to send in csrf-token value in a header for every request by picking in the value from cookie as described here. Since this is to be done at every request, I am setting the default headers for $http in the main module's run function.
Now, If a new tab is opened for the same website, a new csrf token (in cookie) is issued by the server. Since the run function is run only once, the default header for csrf will be old one (for old tab), while the new csrf cookie will be sent to server, resulting in csrf-mismatch.
How to overcome this at a global level?
I want somehow to create a function which will be run everytime the $http is called, so that then I'll override the default headers.
Note: I do not want to set this header value for every $http request.
(Not that I think that it's relevant, but I'm using ui-router)
Edit
This is not just limited to csrf-token, I want to set some other headers too based on the logged in user, which has to be done dynamically (say when one user logs in, and logs out, then another user logs in).
you need to use http interceptor to do this on every request. read more about http interceptors here
below is one such example
module.factory('xsrfTokenInterceptor', function ($q, $http) {
return {
'response': function (response) {
var cookies = response.headers("Set-Cookie");
var token = someCrazyParsing(cookies);
$http.defaults.headers.common["X-CSRFToken"]=token;
return response || $q.when(response);
}
};
});
module.config(function($httpProvider){
$httpProvider.interceptors.push('xsrfTokenInterceptor')
})
How about headers $http(config) parameter.
$scope.getWithHeader = function(){
$http({
method: 'GET',
url: 'http://fiddle.jshell.net',
headers: {
'CustomHeader': 'HelloWorld'
}
}).success(function(){
console.log("success");
});
};
sample code on jsFiddle

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;
});
//..
});

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.

angularjs custom REST action and error handling

I'm having some trouble with error handling in a little angularjs application. I'm interacting with a Flask backend and a Postgres DB.
I have a factory service
appointServices.factory('Appointments', ['$resource', function($resource){
return $resource(someUrl, {}, {
query: { ... }
,
create: {
method: 'POST'
,url: 'http://somedomain:port/new/:name/:start/:end/:treatment'
,params: { start: '#start', end: '#end', name: '#name', treatment: '#treatment' }
,isArray:false
}
});
}
]);
Inside a controller I'm making the following call
Appointments.create($scope.appointment, function(value, responseHeaders) {
// success handler
console.debug('success: ', JSON.stringify(value));
}, function(httpResponse) {
// error handler
console.debug('error: ', JSON.stringify(httpResponse));
});
Here $scope.appointment contains the relevant parameters for the create action.
Now, in the backend I'm able to catch DB errors involving constraints and I'm trying to return an error code with a 'meaningful' message. So I have a python method
def create(name, start, end, treatment):
try:
...
transaction_status = 'ok'
code = 200
except IntegrityError as e:
...
transaction_status = 'IntegrityError'
code = 500
finally:
...
return make_response(transaction_status, code)
Everything works fine, I'm able to talk to the backend, create new data and insert this in the DB. As I said, any violation of the constraints is detected and the backend responds
curl -X POST "http://somedomain:port/new/foo/bar/baz/qux" -v
...
< HTTP/1.0 500 INTERNAL SERVER ERROR
...
IntegrityError
So, the problem is, no matter whether the action create was successful or not, the intended error handler specified inside the controller is always fired. Moreover, I always end up with a status code 404 in the httpResponse. Firebug shows correctly the code 500 as above, though.
Anybody has any idea of why I'm getting this behavior?
Any suggestions on how to improve the error handling mechanism are also welcome.
Thx in advance.
P.S. Following the documentation on $resource I have also tried variations on the factory service call, e.g.
Appointments.create({}, $scope.appointment, successCallback, errorCallback);
Appointments.create($scope.appointment, {}, successCallback, errorCallback);
with the same results.
Update:
Forgot to mention the important fact that I'm interacting with the backend via CORS requests. The POST request in create above is having place with the OPTIONS method instead. As I mentioned everything is working correctly except for the error response.
Under further investigation, I tried to isolate the factory service, in case I did something wrong, and I also tried the approach shown in the credit card example ($resource docs), but with no positive result.
However, I came up with two workarounds. Firstly, I was able to create a plain JQuery POST request, as in the example shown in the docs. This time, the request is not replaced by OPTIONS and I got the error code correctly.
I also managed to connect to the backend with the low-level $http service as follows:
var urlBase = 'http://somedomain:port/new/:name/:start/:end/:treatment';
var url = urlBase.replace(/:name/g, $scope.appointment.name);
url = url.replace(/:start/g, $scope.appointment.start);
url = url.replace(/:end/g, $scope.appointment.end);
url = url.replace(/:treatment/g, $scope.appointment.treatment);
// force method to be POST
var futureResponse = $http({ method: 'POST', url: url });
futureResponse.success(function (data, status, headers, config) {
console.debug('success: ', JSON.stringify(data));
});
futureResponse.error(function (data, status, headers, config) {
console.group('Error');
console.debug(JSON.stringify(status));
console.debug(JSON.stringify(data));
console.groupEnd();
});
This time, as in the case of JQuery, the request is done effectively with POST and error codes are correctly received.
Notice also that I'm not calling $http.post but I set the method to POST as part of the object parameter to $http, otherwise the connection takes places with OPTIONS as before.
Still trying to figure out what is happening with $resource.

Resources