cookie 可以实现不同域共享吗

设置Cookie 的 Domain可以使子域跨域

假设你使用的是 Node.js 和 Express 作为后端服务器,你可以通过 res.cookie 方法来设置 Cookie,并指定 Domain 属性

const express = require('express');
const app = express();

app.get('/set-cookie', (req, res) => {
  res.cookie('myCookie', 'cookieValue', {
    domain: '.example.com', // 注意前面的点号,表示适用于所有子域
    maxAge: 900000, // Cookie 的有效期(毫秒)
    httpOnly: true, // 仅允许通过 HTTP/HTTPS 访问
    secure: true // 仅允许通过 HTTPS 访问(在生产环境中使用)
  });
  res.send('Cookie has been set');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

前端通过请求设置 Cookie

<template>
  <div>
    <button @click="setCookie">Set Cookie</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async setCookie() {
      try {
        await axios.get('http://localhost:3000/set-cookie');
        alert('Cookie has been set');
      } catch (error) {
        console.error('Error setting cookie:', error);
      }
    }
  }
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值