Accept Header在javascript中的应用

Application of the Accept Header in javascript

本文关键字:应用 javascript Header Accept      更新时间:2023-09-26

我正试图在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");

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