nodejs express解决fetch请求和使用Set-Cookie交互,axios\fetch网络请求携带cookie

This Set-Cookie header does not specify the "SameSite" attribute, defaults to "SameSite=Lax", and is blocked because it comes from cross-site responses, not responses to top-level navigation. SetCookie must be set to "SameSite=None" to enable cross-site use.

以上报错为浏览器(google)不支持非https服务设置Set-cookie

解决一、使用https

解决二、在服务端将SameSite = None和secure=true(完整代码在最后)

has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

 fetch请求 credentials: 'include' 服务端代码没有做适配(解决查看下列完整代码)

服务端express代码

const cors = require('cors');
app.use(cors()); // cors解决跨域

app.get('/setCookie', (req,res) => {
    const userId = '123456789';
    // 将 SameSite=None 和 secure=true
    res.cookie('user_id', userId, { sameSite: 'none', secure: true });
    // 设置后的响应请求头 Set-Cookie: user_id=123456789; Path=/; Secure; SameSite=None
    res.send('setCookie');
})

app.post('/getHeaderCookie', (req,res) => {
    // 适配前端 credentials: 'include' 携带请求头 cookie 允许的前端地址
    res.setHeader('Access-Control-Allow-Origin', 'http:/127.0.0.1:18000');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    // 获取请求头cookie数据
    console.log(req.headers.cookie);
    res.send('getList');
})

前端fetch发动请求代码

// 设置cookie 常用于登录接口
fetch('http://127.0.0.1/setCookie', {
  method: 'GET',
}).then((res) => {
  console.log(res, 'res')
})

fetch('http://127.0.0.1/getHeaderCookie', {
  method: 'POST',
  credentials: 'include', // 携带 Cookie
// headers: {
 // 'Token': 'SESSION=MGZ', // 手动添加header值
// },
  body: JSON.stringify({
    encryptParams:'', // post请求参数
  }),
}).then((res) => {
  console.log(res, 'res')
})

在axios中携带cookie

    const service = axios.create({
      baseURL: process.env.VUE_APP_BASE_API, // 环境变量base接口地址 url = base url + request url
      withCredentials: true, // 跨域请求时发送Cookie
      timeout: 60000, // 请求超时
      headers: {
        "Content-Type": "application/json; charset=UTF-8;"
      }
    });

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值