XHR should add Content-type header only for POST

Sending Content-type header causes JSTD (Jetty) proxy to change GET methods into POST.
This commit is contained in:
Vojta Jina 2011-05-03 09:40:39 +02:00 committed by Igor Minar
parent c5f0342ad8
commit 9f56af9c15
2 changed files with 31 additions and 9 deletions

View file

@ -7,10 +7,14 @@ var XHR = window.XMLHttpRequest || function () {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
// default xhr headers
var XHR_HEADERS = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest"
DEFAULT: {
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest"
},
POST: {'Content-Type': 'application/x-www-form-urlencoded'}
};
/**
@ -103,8 +107,9 @@ function Browser(window, document, body, XHR, $log) {
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(extend(XHR_HEADERS, headers || {}), function(value, key){
if (value) xhr.setRequestHeader(key, value);
forEach(extend({}, XHR_HEADERS.DEFAULT, XHR_HEADERS[uppercase(method)] || {}, headers || {}),
function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {

View file

@ -101,16 +101,15 @@ describe('browser', function(){
it('should set headers for all requests', function(){
var code, response, headers = {};
browser.xhr('METHOD', 'URL', 'POST', function(c,r){
browser.xhr('GET', 'URL', 'POST', function(c,r){
code = c;
response = r;
}, {'X-header': 'value'});
expect(xhr.method).toEqual('METHOD');
expect(xhr.method).toEqual('GET');
expect(xhr.url).toEqual('URL');
expect(xhr.post).toEqual('POST');
expect(xhr.headers).toEqual({
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-header":"value"
@ -124,10 +123,28 @@ describe('browser', function(){
expect(code).toEqual(202);
expect(response).toEqual('RESPONSE');
});
it('should not set Content-type header for GET requests', function() {
browser.xhr('GET', 'URL', 'POST-DATA', function(c, r) {});
expect(xhr.headers['Content-Type']).not.toBeDefined();
});
it('should set Content-type header for POST requests', function() {
browser.xhr('POST', 'URL', 'POST-DATA', function(c, r) {});
expect(xhr.headers['Content-Type']).toBeDefined();
expect(xhr.headers['Content-Type']).toEqual('application/x-www-form-urlencoded');
});
it('should set default headers for custom methods', function() {
browser.xhr('CUSTOM', 'URL', 'POST-DATA', function(c, r) {});
expect(xhr.headers['Accept']).toEqual('application/json, text/plain, */*');
expect(xhr.headers['X-Requested-With']).toEqual('XMLHttpRequest');
});
});
describe('defer', function() {
it('should execute fn asynchroniously via setTimeout', function() {
var counter = 0;