Accessing custom http response headers in angularjs - javascript

I am trying to access the header 'error-detail' as you can see in the browser network inspector (link above), the header gets returned. Server-wise I have also added the custom header to the 'Access-Control-Expose-Headers' to allow cross-domain requests as this was suggested to be the fix on other questions.
Below is the request to the server along with the success/error callbacks.
this.signon = function (request, onComplete, onError) {
console.log("Calling server with 'login' request...");
return $http.post("http://localhost:8080/markit-war/services/rest/UserService/login/", request)
.then(onComplete, onError);
};
var onLookupComplete = function(response) {
if (response.data.username)
{
//If user is returned, redirect to the dashboard.
$location.path('/dashboard');
}
$scope.username = response.data.username;
};
var onError = function(response) {
$scope.error = "Ooops, something went wrong..";
console.log('error-detail: ' + response.headers('error-detail'));
};
When I try access the response header as seen below:
console.log(response.headers());
console.log('error-detail: ' + response.headers('error-detail'));
This only outputs:
content-type: "application/json"
error-detail: null
Is there a reason why the error-detail header is not being mapped over to the response object?

I think you are on the right track. To have access to custom headers, your server needs to set this special Access-Control-Expose-Headers header, otherwise your browser will only allow access to 6 predefined header values as listed in the Mozilla docs.
In your screenshot such a header is not present in the response. You should have a look at the backend for this cors header to also be present in the response.

This is a CORS Issue. Because this is a cross-origin request, the browser is hiding most ot the headers. The server needs to include a Access-Control-Expose-Headers header in its response.
The Access-Control-Expose-Headers1 response header indicates which headers can be exposed as part of the response by listing their names.
By default, only the 6 simple response headers are exposed:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
If you want clients to be able to access other headers, you have to list them using the Access-Control-Expose-Headers header.
For more information, see MDN HTTP Header -- Access-Control-Expose-Headers

Related

How to set cookies on a response in a ServiceWorker

In a fetch handler triggered by a page navigation, I tried to do this:
return event.respondWith(new Response('Hello!', {
headers: {
"Set-Cookie": "TestCookie=foo; path=/; Max-Age=60;"
"TestHeader": "foo"
}
}));
Then I loaded any URL in the browser, and got the "Hello!" body. In Chrome devtools, I see the TestHeader set in the network panel. But the cookie is not showing up in the network panel, nor in the Application > Cookies viewer. document.cookie also fails to produce it.
The request is initiated by a page navigation, so there's no opportunity to set credentials: "include" on the fetch from the browser tab.
Is it possible to add a cookie to a response in the ServiceWorker? If not, is it possible to write cookies in any other way?
There's some relevant information in the Fetch specification.
As per https://fetch.spec.whatwg.org/#forbidden-response-header-name:
A forbidden response-header name is a header name that is a
byte-case-insensitive match for one of:
Set-Cookie
Set-Cookie2
And then as per item 6 in https://fetch.spec.whatwg.org/#concept-headers-append:
Otherwise, if guard is "response" and name is a forbidden response-header name, return.
This restriction on adding in the Set-Cookie header applies to either constructing new Response objects with an initial set of headers, or adding in headers after the fact to an existing Response object.
There is a plan to add in support for reading and writing cookies inside of a service worker, but that will use a mechanism other than the Set-Cookie header in a Response object. There's more information about the plans in this GitHub issue.
You may try following:
async function handleRequest(request) {
let response = await fetch(request.url, request);
// Copy the response so that we can modify headers.
response = new Response(response.body, response)
response.headers.set("Set-Cookie", "test=1234");
return response;
}

AJAX request with headers failing

I'm trying to do an AJAX request to https://developers.zomato.com/api/v2.1/search referring to Zomato API
The server has headers:
"access-control-allow-methods": "GET, POST, DELETE, PUT, PATCH, OPTIONS",
"access-control-allow-origin": "*"
The problem is that the API requires additional headers set for user-key. But whenever I set custom headers then chrome would do a pre-flight request by sending an OPTIONS request to the above URL which is failing, and thus the AJAX request is failing as well.
If I don't set the headers, then I don't get a CORS error, but rather a forbidden error from server since I'm not setting user-key header.
Any way to go about this catch-22 situation?
Both Jquery and JavaScript way are failing:
$(document).ready(function () {
$.ajax({
url: 'https://developers.zomato.com/api/v2.1/search',
headers: {
'Accept': 'application/json',
'user_key': 'XXXXX'
},
success: function (data) {
console.log(data);
}
});
});
var xhr = new XMLHttpRequest();
var url = 'https://developers.zomato.com/api/v2.1/search';
xhr.open('GET', url, false);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('user_key', 'XXXXXX');
xhr.send(null);
if (xhr.status == 200) {
console.log(xhr.responseText);
}
Error I'm getting:
OPTIONS https://developers.zomato.com/api/v2.1/search
XMLHttpRequest cannot load https://developers.zomato.com/api/v2.1/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
If somebody wants to reproduce you can get a free user-key here:
https://developers.zomato.com/api
There does not appear to be a work-around for this issue from a browser. The CORS specification requires a browser to preflight the request with the OPTIONS request if any custom headers are required. And, when it does the OPTIONS preflight, it does not include your custom headers because part of what the OPTIONS request is for is to find out what custom headers are allowed to be sent on the request. So, the server is not supposed to require custom headers on the OPTIONS request if it wants this to work from a browser.
So, if the server is requiring the custom headers to be on the OPTIONS request, then the server is just expecting something that will not happen from a browser.
See related answers that describe more about this here:
jQuery CORS Content-type OPTIONS
Cross Domain AJAX preflighting failing Origin check
How do you send a custom header in a cross-domain (CORS) XMLHttpRequest?
Using CORS for Cross-Domain Ajax Requests
And, another user with the same issue here:
Zomato api with angular
It appears the Zomato is not browser friendly, but requires access from a server where you don't have CORS restrictions.
FYI, the error coming back from Zomato is 501 which means NOT IMPLEMENTED for the OPTIONS command. So, it looks like it's not only that the key is not being sent with the OPTIONS command, but that Zomato does not support the OPTIONS command, but that is required for the use of custom headers on a cross-origin request from a browser.
You can't bypass Access-Control-Allow-Headers in preflight response.
However as mentioned by #Jaromanda X in comments, Zomato sends:
Access-Control-Allow-Headers:X-Zomato-API-Key
...meaning you can only send this non-standard header from browser. Also don't go too low-level in request definition when jQuery has pretty and prepared shorthands ...
TL;DR Working example:
$.ajax({
type: "GET", //it's a GET request API
headers: {
'X-Zomato-API-Key': 'YOUR_API_KEY' //only allowed non-standard header
},
url: 'https://developers.zomato.com/api/v2.1/dailymenu', //what do you want
dataType: 'json', //wanted response data type - let jQuery handle the rest...
data: {
//could be directly in URL, but this is more pretty, clear and easier to edit
res_id: 'YOUR_RESTAURANT_OR_PLACE_ID',
},
processData: true, //data is an object => tells jQuery to construct URL params from it
success: function(data) {
console.log(data); //what to do with response data on success
}
});

Accessing response headers on CORS request

I'm using the fetch API to make a cross-domain request similar to the below snippet
window.fetch('http://data.test.wikibus.org/magazines', { method: 'get'})
.then(function(response) {
var linkHeader = response.headers.get('Link');
document.querySelector('#link-header').innerText = 'The Link header is: ' + linkHeader;
});
<span id="link-header"></span>
As you see the Link header (and some other headers too) is not accessible although it is returned in the response. I assume that's a CORS issue, because on local requests all headers are accessible.
Is that by design? Is there a way around that problem?
The resource you are requesting most likely lacks a Access-Control-Expose-Headers header that contains Link as value.
See https://fetch.spec.whatwg.org/#http-access-control-expose-headers and see https://fetch.spec.whatwg.org/#concept-filtered-response-cors for the details of which headers get filtered out of a CORS response.

Angular $http.post and No 'Access-Control-Allow-Origin' header

I have two app with nodejs and angularjs.nodejs app has some code like this :
require('http').createServer(function(req, res) {
req.setEncoding('utf8');
var body = '';
var result = '';
req.on('data', function(data) {
// console.log("ONDATA");
//var _data = parseInput( data,req.url.toString());
var _data = parseInputForClient(data, req.url.toString());
switch (req.url.toString()) {
case "/cubes":
{
and this app host on http://localhost:4000.angularjs app host with node http-server module on localhost://www.localhost:3030.in one of my angularjs service i have some thing like this :
fetch:function(){
var data = '{somedata:"somedata"}';
return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
console.log(cubes);
});
}
but when this service send a request to server get this error:
XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access.
so i search the web and stackoverflow to find some topic and i find this and this . according to these topics i change the header of response in the server to something like this :
res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));
but this dose'nt work.I try with firefox,chrome and also check the request with Telerik Fiddler Web Debugger but the server still pending and i get the Access Control Allow Origin error.
You do POST request, which generates preflight request according to CORS specification: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ and https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your server should also respond to OPTIONS method (besides POST), and return Access-Control-Allow-Origin there too.
You can see it's the cause, because when your code creates request in Network tab (or in Fiddler proxy debugger) you should see OPTIONS request with ORIGIN header

ExtJS 4.2.1: Cannot retrieve HTTP Response headers upon Ext.ajax.request callback

I'm trying to read the headers of the coming response upon Ext.ajax.request.
Here it is the code:
Ext.Ajax.request({ url: 'http://localhost:3000/v0.1/login' ,
method: 'POST',
scope:this,
jsonData: {"_username":username,"_userpwd":password},
success: function(responseObject){
var headers = responseObject.getAllResponseHeaders();
console.info(headers );
Ext.destroy(Ext.ComponentQuery.query('#loginWindow'));
this.application.getController('SiteViewController').showView();
},
failure: function(responseObject){
alert(responseObject.status);
}
});
But the only header that it is printed out in console is:
Object {content-type: "application/json; charset=utf-8"}
All the other headers are missing, but they are present in the chrome inspector!!!
What am I missing? Thanks
Because you're probably doing a cross-domain request, you will only have headers explicitly exposed by the server. Same domain requests expose all the headers.
On the server side you have to add the header "Access-Control-Expose-Headers" with the exhaustive list of headers you want to expose, separated by a coma. In php it would look like this:
header("Access-Control-Expose-Headers: Content-length, X-My-Own-Header");
The headers will indeed be available through responseObject.getAllResponseHeaders() or something like responseObject.getResponseHeader('content-type').
More information about cross-domain requests and headers: http://www.html5rocks.com/en/tutorials/cors/
PS: Ace.Yin had the right answer, but I don't have enough reputation to simply comment.
i ran into the same issue and finally i found the solution here: http://www.html5rocks.com/en/tutorials/cors/
here is the part about the headers:
Access-Control-Expose-Headers (optional) -
The XMLHttpRequest 2 object has a getResponseHeader() method that returns the value of
a particular response header. During a CORS request, the getResponseHeader() method
can only access simple response headers.
Simple response headers are defined as follows:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
If you want clients to be able to access other headers, you have to use the
Access-Control-Expose-Headers header. The value of this header is a comma-delimited
list of response headers you want to expose to the client.
i have not verify it yet, but it seems on the right track :)

Categories