




















2018-11-06更新: 如果在chrome浏览器中过期时间 expiration date显示的是1969。 答案 说明cookie是临时的,只保持在这个会话周期,当浏览器关闭时cookie会被清除。 Unix time was started at the beginning of 1970, that means that -1 is in 1969. And that is a commonly used value for "unknown" if the expected value is usually positive. And for cookies MaxAge with a negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.
2018-08-27更新: 使用cookie前强烈建议先看下MDN的这篇基础文章 创建cookie可以配置的选项 Expires,Secure,HttpOnly,Domain,Path,SameSite。 为避免跨域脚本 (XSS) 攻击,通过JavaScript的 Document.cookie API无法访问带有 HttpOnly 标记的Cookie,它们只应该发送给服务端。
最近在开发一个前后台分离的项目。 前台是 localhost:8080,基于vue,请求用的axios库,后台是地址 localhost:8111,使用的是NodeJS。 也就是前台发起的请求是跨域的。 现在流程是这样的: 前台向后台请求接口,后台会看到set-cookie,可是我发现前端JS 怎么也拿不到 cookie(后来发现是cookie被设置了HttpOnly)。axios的response里没有。但是在chrome里可以看到设置的cookie。 查了文档,当需要跨域请求,前台需要设置 withCredentials 为 true。 这样每次请求会自动带上 cookie,但是后台也需要设置 Access-Control-Allow-Credentials: true, 就不能用*来设置Origin了,即 Access-Control-Allow-Origin:* , 而应该相应的改成Access-Control-Allow-Origin: localhost:8080, 这样就比较尴尬了,到时候前台是对大众开放,需要允许所有来源,难道没有别的办法了?相信标准这么做也是为了安全。 查了也有解决办法。都还没有尝试。 比如
if ($http_origin ~* ( https?://.*\.example\.com(:[0-9]+)?$)) {
add_header Access-Control-Allow-Origin: $http_origin;
}app = express()
app.all('/*', (req, res, next) => {
if (req.headers.origin) {
res.header("Access-Control-Allow-Origin", req.headers.origin)
res.header("Access-Control-Allow-Credentials", true)
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
# 下面一行意义不明确...
res.header("Access-Control-Allow-Headers", "X-Requested-With, AUTHORIZATION")
}
next(); // pass control to the next handler
});
next()其实使用cookie做前后端分离真的没有 token 或 jwt 好用。机密的信息不要放到cookie中比较好。
==== 更新 使用下面的方法在本地可行
if (process.env.NODE_ENV == 'local') {
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
}else {
app.use(cors());
}此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。