1

嘿嘿。我有以下问题:

我用这个

res.writeHead(200, {
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
});

将响应标头写入客户端。

但是现在,我想更改上面的代码以提供预定义的标头。像这样的东西:

var defresheads = { "X-Frame-Options": "deny", "X-Powered-By": servername };

res.writeHead(200, {
    defresheads,
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
});

现在,当我运行脚本时,它会显示以下内容:

/home/dontrm/dontrm.js:47
            defresheads,
                       ^
SyntaxError: Unexpected token ,

还有另一种方法可以做到这一点吗?

4

1 回答 1

1

使用辅助函数来连接您的标头对象,例如

function jsonConcat(o1, o2) {
    for (var key in o2) {
        o1[key] = o2[key];
    }
    return o1;
}

然后您可以按如下方式使用它:

var defresheads = { "X-Frame-Options": "deny", "X-Powered-By": servername };
res.writeHead(200, jsonConcat(defresheads, {
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
}));
于 2012-11-17T13:01:27.823 回答