项目中浏览器发送请求自动携带Cookie

本文介绍了如何在umi项目中通过umi-request模块设置credentials为'include'以保存跨域cookie,并提到了fetch和axios的相应配置。同时,强调了设置Domain和正确访问方式对于cookie存储的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们要在请求头中添加上这个配置:
credentials: ‘include’。

我的项目使用的umi框架,代码如下

import request from 'umi-request';
import { message } from 'antd';
import lodash from 'lodash';


export default function (url: string, options?: any) {
  return new Promise((resolve, reject) => {
    const newOptions = {
      ...options,
      credentials: 'include',
      headers: {},
    };
    let apiUrl = url;
    request(apiUrl, { ...newOptions })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

1 用fetch需要在请求头加上credentials : 'include' 才能保存cookie

2 如果自己项目中使用的是axios,那么需要配置

withCredentials: true,

const opts: any = {
    url,
    method: 'post',
    headers: {
        "Content-Type": "application/json;charset=utf-8",
    },
    baseURL: '',
    data: { ...params },
    timeout: 30000,
    withCredentials: true,
    responseType: 'json',
    responseEncoding: 'utf8',
    maxContentLength: 2000,
}
axios({ ...opts }).then(res => {})

服务端

//生成token
const token = jwt.sign(user, "express-admin", {
    expiresIn: 180, //3分钟过期
	//algorithm: 'RS256'//加密算法 默认HS256
});
res.cookie("user", token, {
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000), //一天后过期
    httpOnly: true,
    Domain: "192.168.0.9",
    Path: "/",
});

注意:

1 Domain必须设置否则不会存储cookie

2 在访问浏览器的时候需要使用ip访问,不要使用localhost访问,否则不会存储cookie

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值