Reputation: 133
I'm trying to insert an Accept header in the json file. But I don't know why the test does not work. Can you help me? Here is my code:
function doJSONRequest(type, url, headers, data, callback){
var r = new XMLHttpRequest();
if(type && url && headers && callback && (arguments.length == 5)){
r.open(type, url, true);
if((type != "GET") && (type != "POST") && (type != "PUT") && (type != "DELETE")){
throw new Error('The value is not recognized')
} else if((type == "POST") || (type == "PUT") || (type == "GET") || (type == "DELETE")) {
try {
if(data === undefined) {
data = null;
}
else if(typeof data === 'object'){
r.send(JSON.stringify(data));
} else {
throw new Error("The data is undefined")
}
} catch (e) {
throw new Error("The data has no JSON format")
}
} else if((type == "POST") || (type == "PUT")){
r.setRequestHeader("Content-type","application/json");
r.send(JSON.stringify(data));
}
And here is the test I use:
var expectedGETHeader = {
"Accept": "application/json"
}
doJSONRequest("GET", baseUrl, headers, null, callback1);
setTimeout(function(){
QUnit.start();
assert.deepEqual(requests[4].requestHeaders, expectedGETHeader, "should set the \"Accept\": \"application/json\" header for GET requests");
},100);
Can you help me passing it? The specific error is:
should set the "Accept": "application/json" header for GET requests
Expected:
{
"Accept": "application/json"
}
Result:
{}
Diff:
{
"Accept": "application/json"
} {}
SOLUTION Adding the line of code after opening it r.setRequestHeader("Accept", "application/json");
Upvotes: 0
Views: 317
Reputation: 2519
I don't see the Accept
header getting set anywhere. Maybe you could do that right before calling r.send(JSON.stringify(data));
, like so:
if(data === undefined) {
data = null;
}
else if(typeof data === 'object'){
r.setRequestHeader('Accept', 'application/json'); // <-- this was added
r.send(JSON.stringify(data));
} else {
throw new Error("The data is undefined")
}
Upvotes: 1