在javascript中应用Accept Header

时间:2014-10-31 19:01:13

标签: javascript json

我正在尝试在json文件中插入Accept标头。但我不知道为什么测试不起作用。你能帮助我吗?这是我的代码:

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(“Accept”,“application / json”);

1 个答案:

答案 0 :(得分:1)

我没有看到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")
        }
相关问题