Node.js 为什么未发送设置的Cookie标头?--使用Restify
我正在为一个节点应用程序开发身份验证系统。登录页面向认证端点发送AJAX请求,然后端点查询用户数据库以确定凭据的有效性。如果端点确定凭据有效,我将使用Express的Node.js 为什么未发送设置的Cookie标头?--使用Restify,node.js,authentication,express,cookies,restify,Node.js,Authentication,Express,Cookies,Restify,我正在为一个节点应用程序开发身份验证系统。登录页面向认证端点发送AJAX请求,然后端点查询用户数据库以确定凭据的有效性。如果端点确定凭据有效,我将使用Express的res.cookie()方法在客户端创建一个cookie,其中包含稍后请求的身份验证信息 身份验证工作正常,响应被发送回用户,但是当我查看开发人员工具时,我没有看到authorizationcookie,也没有提到Set cookie头。有什么好处 进一步资料: 响应上的标题 restify.CORS.ALLOW_HEADERS.p
res.cookie()
方法在客户端创建一个cookie,其中包含稍后请求的身份验证信息
身份验证工作正常,响应被发送回用户,但是当我查看开发人员工具时,我没有看到authorization
cookie,也没有提到Set cookie
头。有什么好处
进一步资料:
响应上的标题
restify.CORS.ALLOW_HEADERS.push('Accept-Encoding');
restify.CORS.ALLOW_HEADERS.push('Accept-Language');
restify.CORS.ALLOW_HEADERS.push('authorization');
restify.CORS.ALLOW_HEADERS.push('token');
server.use(restify.CORS({
origins: ['*'],
credentials: true,
headers: ['token']
}));
/* break */
server.opts(/\.*/, function (req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', restify.CORS.ALLOW_HEADERS.join(', '));
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Origin', res.headers.origin);
res.header('Access-Control-Max-Age', 0);
res.header('Content-type', 'text/plain charset=UTF-8');
res.header('Content-length', 0);
res.send(200);
next();
});
认证api的相关部分
function authHandler(req, res, next) {
authMan.authenticate(req.params.username,req.params.password).then(function(userdata){
/*d*/console.log('userData:'+userdata);
// jwt library for JSON web tokens
const authorization = jwt.sign(
{'sub': userdata.username, 'roles': authMan.getGroups(userdata)},
// global
authSecret,
{issuer:'myCompany.com'}
);
// Only send the client the user's username and display name
var strippedData = {};
strippedData.username = userdata['username'];
strippedData.displayName = userdata['displayName'];
// Disable https when not in prod
var useHttps = true;
if (process.env[NODE_ENV] === 'dev') {
useHttps = false;
}
res.cookie('authorization', authorization, {
httpOnly: true,
secure: useHttps
});
/*d*/console.log('Sent the request back!');
res.send({
status: 'OK',
userdata: strippedData
});
next();
},function(err){
/*d*/console.log('authHandler error: '+err);
res.status(401).send({
status: 'ERROR',
error: err
});
next();
});
metrics.log(etc);
next();
}
您会注意到,在上面的代码中,有一个调试printf说“将请求发送回!”,而响应被发送回服务器,并且它包含正确的内容,该语句从未出现在我的控制台中,即使它出现在
res.send()
之前,经过检查和同事的帮助,问题是res.cookie()
未定义。不知怎的,我突然想到我们使用的服务器restify.js
,是express.js
的超集。不是!我应该使用的函数是res.setCookie()
谢谢你回来发帖。如果它确实解决了您的问题,请接受您自己的答案,这样其他人就会知道有解决方案。