AngularJS $http object not showing all headers from response - javascript

I'm having a problem with AngularJS's $http service not returning all of the headers from the API I'm polling. Here's what I've got:
$http({
method: 'POST',
withCredentials: true,
url: 'http://api.mydomain.com/query',
data: JSON.stringify(parameters)
})
.success(function(data, status, headers, config){
... // setting some scope parameters based on data
console.log(headers());
})
I can tell through the network tab in Chrome that a bunch of response headers are being returned by the API (I'm particularly interested in the X-Pagination-Total-Items header).
Here's a screenshot of the network tab from the request:
But the console.log statement above (which should output all headers) only returns two:
Any idea what's going on? How do I actually access all of the headers coming back from the AJAX call?
Thanks,
-Nate

Turns out that the Access-Control-Expose-Headers cannot accept a wildcard. We needed to specify exactly which headers the client should have access to, and then it worked.

Related

How to request data from an API using AJAX.

I want to make a post request to an API (http://nairabox.com/food_documentation/) using Ajax but am kind of confused on how to go about it.
This is what I have tried so far:
$.ajax({
type: "POST",
url: "https://mapp.nairabox.com:8443/api/v1/food/",
dataType : "json",
data: { case: "browse"},
headers: {
'case': 'browse'
},
success: function(data){
console.log('success');
}
})
So far, it is returning no result.
What could I be getting wrong?
The API doc is here (http://nairabox.com/food_documentation/)
The documentation you link to does not say to add any custom HTTP request headers.
You, however, are doing so here:
headers: {
'case': 'browse'
},
The case data belongs in the data and only in the data.
By adding the custom header, you are preventing the request from being simple and triggering a preflight OPTIONS request which the server does not accept.
Remove the above and you will get a response (and your success function will fire … you should probably do something with the data argument though)
Note, also, that the documentation says you should pass latitude and longitude as well as case.
Unless you add them, the response you get is unlikely to be useful.

POST data to a Google form with AJAX

I am trying to post data to a from AJAX to a Google form, but even though it reports success with a statusCode of 0, the data never appears in the form:
var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"};
postToGoogle("1FAIpQLSf4w1OQGsIncaiqXlmfAl4jYSt-e4Zx3xVJa7Weob4LnQbRZQ",dat);
function postToGoogle(id, dat) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
url: "https://docs.google.com/forms/d/e/"+id+"/formResponse",
data: dat,
type: "POST",
dataType: "xml",
xhrFields: { withCredentials: true },
statusCode: {
0: function() { console.log("OK") },
200: function() { console.log("error") },
}
});
}
It generates a CORS error, but supposedly, the POST should go through anyway.
For those looking to do this as of April 2019
I was working on this today. The current answer is as follows:
Each field in the Google Form has a unique ID. In order to retrieve it, get a pre-filled link by filling out all relevant form fields you wish to programatically submit
Note: In order to ensure the URL is accessible without restriction, you'll also want to disable restriction to your domain only (for GSuite paying users)
Then, copy the link and paste in your browser. The URL has a base format as follows:
https://docs.google.com/forms/d/e/[FORMID]/formResponse
Each param is a key/value pair of type: entry.XXXXXX=value
The prefilled link will give you the value of XXXXX for each relevant field
Request must be made with following headers:
Method: GET
Content-Type: application/x-www-form-urlencoded
The final request looks like this
https://docs.google.com/forms/d/e/123332233bsj333/formResponse?entry.123456=value1&entry.2333442=value2&submit=Submit
Don't forget to append submit=Submit at the end of your request!
It generates a CORS error, but supposedly, the POST should go through anyway.
While it is possible to make a successful POST request, get a CORS error, and be unable to read the response, this is only true for Simple Requests.
Because your request has:
Custom headers (Access-Control-Allow-Origin and Access-Control-Allow-Methods, which are response headers and have no business being on a request in the first place)
Credentials (i.e. you have set withCredentials: true)
… it is a Preflighted Request.
Before the browser will make the POST request, it will make an OPTIONS request to ask permission.
Since it doesn't get permission, the request fails.
Note that even if you did turn it into a simple request and make the POST successfully, you would still get a status of 0. You can't read the status when there is a CORS error.

How to return an error with Angular http if the data is html?

I'm using Angular's http function to access my remote API service.
At the moment, my API service is offline, and if users try to access it, it still throws a 200 status which is 'ok' with Angular. Therefore, my success callback is always called instead of my error callback. Weird thing is, if I use a REST client, such as POSTman, it has a status of 404?
Here is my function to call my API (using jQuerys $.param() function for URL friendly post parameters):
$http({
method: 'POST',
url: "http://mydomain/api/login",
data: $.param({
username: "test",
password: "test"
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(successCallback(response), errorCallback(response));
Here is the response it gives when logged:
{data: "
↵<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN…r at [my ip address] Port 80</address>↵</body></html>↵", status: 200, config: Object, statusText: "OK"}
The response when the API is working is usually something along the lines of:
{
data: {
id: 123
},
status: 200,
config: object,
statusText: 'ok'
}
Sure, theres a few dodgy things that I could do here such as writing a http interceptor to check if data is of type object, yet that's not really the answer I'm looking for here since some of my API calls just return a boolean value.
I also tried changing the 'Content-Type' to 'application/json', yet no luck.
I need my error callback to be used if my API is down. Is there an elegant solution to this?
It all sounds a bit hacky, the most appropriate approach I can think of is to send a 404 / 500 from the API endpoints until it comes online.
Otherwise, try to set an Accept header:
{
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}

Angular $http empty error object on failed requests

I'm posting successfully to my server , however when requests fails the error object is empty and i cannot construct logic based on the error code
Here is the code and what i see on DEV tools
$http({
method: 'POST',
url: 'my remote api/',
data: {'Account' : $scope.userPhoneNumber, 'Initiator' : initiator.toString()},
headers: {"Authorization": "Basic register:register"}
}).
then(function (response) {
console.log(response.data.AuthenticationUid);
openModalWindow(initiator, response.data.AuthenticationUid);
}, function (data) {
console.log(data);
$scope.phoneNotFound = true;
});
As you can see the printed data object shows status as -1 while it should show 404....
The console output indicates that you are not successfully POSTing to the server. Your OPTIONS request is successful, but your post fails due to missing 'Access-Control-Allow-Origin' headers which is indicative of a CORs error.
Without knowledge of your server it's a bit hard to give you an exact solution, but searching for something along the lines of 'setting up CORS in ' should get you on the right track.

Angular.js ie ajax request issue

I have a problem with angular.js ajax call with IE. The first time I do the request, all is working good (I get the good result). But when I do an other ajax call (same request) without refreshing the page, the result look to be the same as the first call, even if it shouldn't be the same.
Here's how my request look like :
this.getemploye = function (isaftersave) {
$http({
url: 'Contact.svc/getemployee',
method: "GET"
}).success(function (data) {
//The data result is always the same with IE.
});
};
Note that I have no problem with Chrome and FireFox. The version of IE is 11.
IE will aggressively cache all ajax calls (actually pretty much everything). You will need to set the cache options on the HTTP response headers from your servers.
You will need to add the Cache-Control header to your ajax response sent from the server if you do not want it cached.
Cache-Control: no-cache, no-store
As an extra measure you should set cache:false in your $http call
$http.get('https://api.myapp.com/someresource', { cache: false });
If you haven't got access to modify the server you could always just append a random query string onto the url every time This will force IE to re-issue the request as it won't have seen that url before.
this.getemploye = function (isaftersave) {
$http({
url: 'Contact.svc/getemployee?nocache=' + new Date().toISOString(),
method: "GET"
}).success(function (data) {
});
};

Categories