二级域名(Subdomain)是指在顶级域名(如.com、.org)下的一个子域名。例如,blog.example.com
中的 blog
就是一个二级域名。Cookie 是一种存储在用户浏览器中的小型数据片段,用于跟踪用户会话和存储用户偏好设置。
example.com
。blog.example.com
、shop.example.com
。en.example.com
和 zh.example.com
。Domain
属性如果没有正确设置,可能导致无法在不同二级域名之间共享。Domain
属性为父域名,例如 example.com
,这样所有二级域名都可以访问该Cookie。Domain
属性为父域名,例如 example.com
,这样所有二级域名都可以访问该Cookie。document.cookie = "name=value; domain=example.com; path=/";
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://blog.example.com");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上方法,可以有效解决二级域名读取Cookie的问题。
领取专属 10元无门槛券
手把手带您无忧上云