I do get the response data, but I can't get my custom HTTP header data.
Yes, this is a cross-domain request. I am doing an Ajax request with Javascript. I've tried this with XMLHttpRequest and also jQuery $.ajax. I've done my server settings, I have these set when sending data:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET
I do get the response data that I want. But I can't get full HTTP header response.
With PHP, I set the following before sending the text response. So I assume that I should get it with getAllResponseHeaders().
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('My-Own-Test: nodatahere');
But here's what I got.
Content-Type: text/plain; charset=x-user-defined
Cache-Control: must-revalidate, post-check=0, pre-check=0
Expires: 0
It's missing the My-Own-Test
. Just for reference sake, here's my Javascript:
var formData = new FormData();
formData.append('username', 'my_username');
formData.append('book_id', 'test password');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://mydomain.com/proc.php', true);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.onload = function(e) {
console.log(this.getAllResponseHeaders());
};
xhr.send(formData);
I even tried it with jQuery... same result.
var data_to_send = {
username: 'my_username',
password: 'test_password'
};
var ajaxObj;
ajaxObj = $.ajax({
url: "https://mydomain.com/proc.php",
data: data_to_send,
type: "POST",
beforeSend: function ( xhr ) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function ( data ) {
console.log( ajaxObj.getAllResponseHeaders() );
});
Still... no luck.
But if I go through Firebug or Chrome's Developer Tool, I can see that those tools do return full HTTP header information, including Content-Length
, Content-Encoding
, Vary
, X-Powered-By
, Set-Cookie
, Server
, and of course My-Own-Test
.
I wanna thank jbl for pointing me to the right SO question. I got it now...
So, OK... the answer. If you ever wanted to set your own HTTP Header information, and then fetch it using cross-domain Ajax, or something like that, here are some extra HTTP Header you should set on your server side, before sending the response text.
Example above uses PHP. But use your own language, what ever you use to set them.
When I asked this question, I had all of that except
Access-Control-Expose-Headers
. After putting that in, my Javascript Ajax can read the content of HTTP Header Custom-Header.