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」);