2014-12-07 57 views
3

在node.js中(在Connect.js运行此),我能够设置醚位置或设置Cookie与writehead,但不两者在同一时间。目前,下方设置了库克,但URL不重定向到新的位置:的Node.js - writeHead同时设置“位置”和“设置Cookie”

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() } 
} 

在一个侧面说明,我做这行的学习经验,不希望使用任何预先编写的插件。

回答

3

Response#writeHead期望标题是一个对象而不是数组参数列表。

Node HTTP documentation定义了以下特征:

response.writeHead(statusCode, [reasonPhrase], [headers]) 

如果你想在多个头通过上面的代码应改为:

response.writeHead(302, { 
    Location: 'https://staging.dx.host.com' + req.url', 
    'Set-Cookie': 'fake-token=5b49adaaf7687fa' 
}); 

reasonPhrase[]意味着其可选的,根据参数的类型推断您提供给函数的内容。除非它包含对变量名称无效的字符(如-),并且您不需要用引号将key对象的一部分包装起来(-),并且单个'将适用于所有字符串 - 在'"之间的javascript没有区别。

+0

只是要注意:我不能设置其他主机上的cookie重定向...在代理上是的,但不是在重定向 – dman 2014-12-08 14:11:28

+1

是的,我没有想过这个,但HTTP规范不允许在302上。 – tkone 2014-12-08 15:04:32