[英]Node.js - writeHead to set both “Location” and “Set-Cookie”
在node.js中(在Connect.js中運行),我可以使用writehead設置ether或者Set-Cookie,但不能同時設置兩者。 目前,下面設置了cooke,但URL沒有被重定向到新位置:
function foo(req, res, next) {
var url = /container-templates/;
if (url.test(req.url)) {
console.log(url.test(req.url));
console.log(req.url);
res.writeHead(302, ["Location", 'https://staging.dx.host.com' + req.url],
["Set-Cookie", "fake-token=5b49adaaf7687fa"]);
res.end();
} else { next() }
}
在旁注中,我這樣做是為了學習體驗,並且不想使用任何預先編寫的插件。
Response#writeHead
期望標頭是Object而不是數組參數列表。
Node HTTP文檔定義了以下簽名:
response.writeHead(statusCode, [reasonPhrase], [headers])
如果您想傳入多個標頭,則上面的代碼應為:
response.writeHead(302, {
Location: 'https://staging.dx.host.com' + req.url',
'Set-Cookie': 'fake-token=5b49adaaf7687fa'
});
reasonPhrase
上的[]
表示它是可選的,並根據參數的類型推斷您為函數提供的內容。
此外,您不需要將對象的key
部分用引號括起來,除非它包含對變量名無效的字符(如-
。)並且單個'
將對所有字符串執行 - 在javascript中沒有區別之間的'
和"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.