0
我试图在JSON文件中插入一个Accept头。但我不知道为什么测试不起作用。你可以帮我吗?这里是我的代码:接受头在javascript中的应用
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));
}
,这里是测试我使用:
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);
你能帮我传球呢?特定的错误是:
should set the "Accept": "application/json" header for GET requests
Expected:
{
"Accept": "application/json"
}
Result:
{}
Diff:
{
"Accept": "application/json"
} {}
SOLUTION 添加的代码行打开后 r.setRequestHeader( “接受”, “应用程序/ JSON”);