Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Created January 3, 2018 08:15
Show Gist options
  • Save leizongmin/0b9c94ef7988eec13e2e48ff5ac8a3ad to your computer and use it in GitHub Desktop.
Save leizongmin/0b9c94ef7988eec13e2e48ff5ac8a3ad to your computer and use it in GitHub Desktop.
跨域共享Cookie示例
{
"name": "cookie example",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"connect-redis": "^3.3.3",
"cookie-parser": "^1.4.3",
"express": "^4.16.2",
"express-session": "^1.15.6"
}
}
const express = require("express");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const RedisStore = require("connect-redis")(session);
const cookieOptions = {
// 如果主站为 xxxx.com,则此值设置为 .xxxx.com (正式和测试环境均一样)
// 比如 xxx.com, www.xxx.com, test.xxx.com, abc.test.xxx.com 均能获取到这些 cookie
domain: ".localexample.com",
httpOnly: true,
path: "/",
maxAge: 3600000 * 24 * 365
};
const app = express();
app.use(cookieParser());
app.use(
session({
store: new RedisStore({}),
secret: "secret key",
resave: false,
cookie: cookieOptions
})
);
app.get("/", function(req, res) {
const v = process.uptime();
const oldv = req.session.v;
console.log(req.headers.host, v);
req.session.v = v;
res.cookie("hello", v, cookieOptions);
res.json({ current: v, session: oldv, cookies: req.cookies });
});
app.listen(80, () => {
console.log("server is running...");
console.log(cookieOptions);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment