angularjs, $http 304 error, modify data property - angularjs

we are using the Ionic framework and AngularJS to create a mobile app with phone gap build. We have a call to our api to get an array of items using $http.get, we are adding an Etag in the header if we already have data in cache.
If the data on the server has not changed we get a 304 error which is ok. We are having trouble modifying the data property on the response object form the server to our chached data in local storage.
Any help is appreciated. Thanks
return $http({
method: 'GET',
url: 'http:example.com',
params: params,
headers: customHeader
})
.success(function(data, status, headers, config) {
// do some stuff
})
.error(function(data, status, headers, config) {
if(status == '304') {
alert('this data has not changed');
data = chachedData
// change data to chached data??
}
});

HTTP 304 header code means Not modified, it's not an error. According to the RFC 2616 of HTTP 1.1, the server only sends back headers, not the response which tells the browser to use the response that it had already in cache.
It should be used to avoid heavy network traffic.
But in your case, if you want to do some cache invalidation, this is not the way (but I don't think this is what you wan't to do)
On the other hand, angular will always put 200 in status (even if it is a 304) and you shouldn't have to bother about keeping your data up to date, since you retrieve the fresher value each time (without bothering if it's from a cache in the server or fresh data from the server).

Related

Getting status code in AngularJS 1 on service call

Once the service call is done, I was able to see the status code in General, Response Headers in Chrome Dev Network tab for the production URL. But for the test environments, the status code is being displayed in General but not in Response Header.
Why the status code is not displayed in Response header for test Environments.
How to access status code from General Header in AngularJS.
headers().status in the transformResponse method is always fetching from Response header. So for test environments, I was not able to get the status code.
Any other way to get the status code in AngularJS, I tried passing 2nd param in the success Callback, but I don't get any value for the status code
If you're asking "How to access the status code from the response in AngularJS", it should always be in the response body.
You can get it by writing the following code in your service:
this.requestInformation = function() {
return $http({
method: 'GET',
url: 'Your url'
}).then(function (response) {
console.log(response.status)
return response;
})
}
I hope that answered your question! Let me know if it works for you.

Why isn't my AngularJS post receiving data from the server?

I am posting to the server using the following in AngularJS:
$http.post('/myurl', {my: "data"}, function(data, status, headers, config) {
console.log("returned");
});
In Chrome Developer Tools, the server is sending back a 200 OK status message. However, my callback is never triggered (i.e. nothing printing to the console). Why is AngularJS not printing the message even though the server returns OK?
I've not seen request written like that, generally you want to do something like:
$http.post('/myurl', {my: "data"})
.success(function(data) {
console.log("returned");
});
or
$http.post('/myurl', {my: "data"})
.then(function(data) {
console.log("returned");
});
you can try
return $http({url: '/myurl' , method: "POST",data:my});
you can also click on F12 chrome console to see the exact error
in order to serr the results data you can add
$http({url: '/myurl' , method: "POST",data:my}).then(
function(result){
console.log(result);
}

Recaptcha angularjs verify user's answer

I am using the following plugin https://github.com/VividCortex/angular-recaptcha in order to use recaptcha at a login form.
I am using the following code for verification
$http({
url: 'https://www.google.com/recaptcha/api/verify',
method: 'POST',
params: {privatekey: "key", remoteip: "userip", challenge: "challenge", response: "user_answer" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
console.log(data);
if (valid) {
console.log('Success');
alert('Success');
} else {
console.log('Failed validation');
alert('Fail');
// In case of a failed validation you need to reload the captcha because each challenge can be checked just once
//vcRecaptchaService.reload();
}
});
But google server is not returning anything.
I updated the code but no luck.
I think you have a typo in your code:
post: 'GET'
Change that to method: 'GET' or method: 'POST'.
You can check out angular documentation on http to make sure you've written all the params right.
If this wasn't the source of your problems, you should post more details about your issue (what do you see in your networkl console for example).
Keep in mind that recaptcha validation must be done at server-side. I'm not 100% sure that you are doing that in the browser, but your code looks like it.
As Miguel Trias stated, you shall not validate directly from angularjs/javascript client, instead you should send the challenge and response field to your server and validate then.
Therefore you can use the uri you used (https://www.google.com/recaptcha/api/verify) or a plugin, e.g. if you use php see https://developers.google.com/recaptcha/docs/php. I'd prefer a plugin because it will save work.
Furthermore keep in mind that your private key should not be used in the client, this is why it is called private. It is only used to communicate between your server and the reCaptcha servers. The public key is used to communicate between your client and the reCaptcha servers.
For more info read the Overview

How do I remove the default headers just for specific XHR requests in AngularJS?

99% of my ajax calls need a specific "X-API-TOKEN" to authenticate and communicate with my Rails REST API. But I'm also making a call to one thrid party API and I keep getting an error saying "Request header field X-API-TOKEN is not allowed by Access-Control-Allow-Headers."
Everything works fine if I delte the header right before the call, and a work around would be to delete and then re-add after the call, but is there an easier way than this:
apiToken = $http.defaults.headers.common["X-API-TOKEN"]
delete $http.defaults.headers.common["X-API-TOKEN"]
$http(
method: "GET"
url: 'http://...}}'
).success((data, status, headers, config) ->
).error (data, status, headers, config) ->
$http.defaults.headers.common["X-API-TOKEN"] = apiToken
Set the desire header/headers to undefined like this, then it will not affect the global settings.
$http( {
method: 'GET',
url: 'someurl',
headers: {
'X-API-TOKEN': undefined
}
}
)
The $http service config object allows you to override the http header send for a specific request. See config property headers.
This can take a list of headers or a function that return a list of headers. So for the non auth header request make a copy of the default headers remove the header you dont require and then make the request. You can store this for later use.
See $http documentation

angularjs $http.jsonp goes to .error instead of .success even when 200 is received

I'm building an AngularJS app which calls a NodeJS server that gets data from a DB.
The NodeJS returns a JSON.stringify(someArrayWithData).
Here is the AngularJS code:
$scope.getMainGroups = function(){
$http.jsonp("http://127.0.0.1:3000/get/MainGroups?callback=JSON_CALLBACK").success(function(data, status, headers, config) {
$scope.MainGroups = data;
}).error(function(data, status, headers, config) {
$scope.MainGroups = status;
});
};
$scope.MainGroups is going to the .error instead to the success even when I can see in the chrome debugger that the result came back (200 ok).
What am I missing?
You must return a valid JSON response on the server side. The 200 OK is just the GET request that is injected into the DOM. I bet you are not returning a valid JSON response from the server with right response code.
Here is an example on how to construct the response on the server side (PHP):
Simple jQuery, PHP and JSONP example?
As answered here you need to change the NodeJS response. The JSONP answer needs to start with the exact text that AngularJS added in the URL (for example 'angular.callbacks._1').
// changes in your server script used by NodeJS
// Required for JSONP calls, 'callback' matches the '?callback=JSON_CALLBACK'
app.set('jsonp callback name', 'callback');
// ... in your response change json to jsonp
res.jsonp(votes);
After doing these changes, when the server detects a 'callback' in the parameters, answers like this:
/**/ typeof angular.callbacks._1 === 'function' &&
angular.callbacks._1([{"votes":3,"title":"new topic", etc...
Now yes, AngularJS correctly calls back the 'success' function.

Resources