我们要在请求头中添加上这个配置:
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