Accept头在javascript中的应用
我试图在json文件中插入一个Accept头。但我不知道为什么测试不起作用。你能帮助我吗?这是我的密码:Accept头在javascript中的应用,javascript,json,Javascript,Json,我试图在json文件中插入一个Accept头。但我不知道为什么测试不起作用。你能帮助我吗?这是我的密码: function doJSONRequest(type, url, headers, data, callback){ var r = new XMLHttpRequest(); if(type && url && headers && callback && (arguments.length == 5)){ r.op
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"
} {}
解决方案
打开代码行后添加代码行
r、 setRequestHeader(“接受”、“应用程序/json”) 我没有看到
Accept
标题被设置到任何地方。也许您可以在调用r.send(JSON.stringify(data))之前就这样做代码>,如下所示:
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")
}
if(数据===未定义){
数据=空;
}
else if(数据类型==='object'){
r、 setRequestHeader('Accept','application/json')//