Skip to content

Commit 87066d0

Browse files
committed
working on ajax cors issue #187
1 parent 0eab82b commit 87066d0

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

ajax-test.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,48 @@ if(typeof XDomainRequest === 'undefined') {
108108
start();
109109
});
110110
});
111+
112+
// Test GET CORS:
113+
QUnit.asyncTest("GET CORS should set content-type header (#187)", function () {
114+
115+
var hasCorrectHeader, restore;
116+
restore = makeFixture(function () {
117+
this.open = function (type, url) {
118+
};
119+
120+
this.send = function () {
121+
this.readyState = 4;
122+
this.status = 200;
123+
this.onreadystatechange();
124+
};
125+
126+
this.setRequestHeader = function (header, value) {
127+
if (header === "Content-Type" && value === "application/x-www-form-urlencoded"){
128+
hasCorrectHeader = true;
129+
}
130+
var o = {};
131+
o[header] = value;
132+
this.responseText = JSON.stringify(o);
133+
};
134+
});
135+
136+
ajax({
137+
url: "http://query.yahooapis.com/v1/public/yql",
138+
data: {
139+
fmt: "JSON",
140+
q: 'select * from geo.places where text="sunnyvale, ca"',
141+
format: "json"
142+
}
143+
}).then(function(response){
144+
QUnit.ok(hasCorrectHeader, "Content-Type for GET CORS should be set to `application/x-www-form-urlencoded`");
145+
restore();
146+
start();
147+
}, function(err){
148+
QUnit.ok(false, "Should be resolved");
149+
restore();
150+
start();
151+
});
152+
});
111153
}
112154

113155
if(System.env !== 'canjs-test' && __dirname !== '/') {

ajax.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,14 @@ module.exports = namespace.ajax = function (o) {
159159
}
160160
xhr.open(type, url);
161161

162+
var isJson = o.dataType.indexOf("json") >= 0;
162163
if (isPost) {
163-
var isJson = o.dataType.indexOf("json") >= 0;
164164
data = (isJson && !o.crossDomain) ?
165165
(typeof o.data === "object" ? JSON.stringify(o.data) : o.data):
166166
$._formData(o.data);
167167
xhr.setRequestHeader("Content-Type", (isJson && !o.crossDomain) ? "application/json" : "application/x-www-form-urlencoded");
168+
} else if (type === "GET" && o.crossDomain){
169+
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
168170
}
169171
// X-Requested-With header
170172
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest" );

test.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<title>can-util/dom/ajax/ajax test</title>
5+
</head>
6+
<body>
7+
<div id="qunit-fixture"></div>
8+
<script src="../../node_modules/steal/steal.js"
9+
data-main="can-util/dom/ajax/ajax-test"></script>
10+
</body>
11+
</html>

0 commit comments

Comments
 (0)