Javascript node.js在res.writeHeads()函数中使用一个变量

Javascript node.js在res.writeHeads()函数中使用一个变量,javascript,node.js,variables,object,hyperlink,Javascript,Node.js,Variables,Object,Hyperlink,你好。我有以下问题: 我用这个 res.writeHead(200, { "Content-Length": template["stylecss"].length, "Connection": "Close", "X-XSS-Protection": "1; mode=block", "Server": servername, "Content-Type": "text/css" }); 将响应头写入客户端 但是现在,我想更改上面的代码以提供预定义的头

你好。我有以下问题:

我用这个

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 ,

还有其他方法吗?

使用helper函数连接头对象,如

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"
}));

使用一个helper函数连接头对象,如

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"
}));