簡體   English   中英

node.js在res.writeHeads()函數中使用變量

[英]node.js Use a variable inside the res.writeHeads() function

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”:“拒絕”,“ X-Powered-By”:服務器名};

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 ,

還有另一種方法嗎?

使用輔助函數來連接標題對象,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM