node.js使用res.writeHeads()函数内的变量

时间:2012-11-17 12:57:04

标签: javascript node.js variables object hyperlink

Heyo在那里。我有以下问题:

我用这个

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 ,

还有其他办法吗?

1 个答案:

答案 0 :(得分: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"
}));