如何解决在React中将set-cookie值保存到浏览器cookie
我从服务器获取了此cookie值,并将其保存到浏览器中。
Set-Cookie: succeeedd=noooo!; Path=/
我尝试过
const res = yield axios.post(`${config.authURL}/login`,data,{
headers: {
'Content-Type': 'application/json',Cookie: 'cookie1=value',},});
和
const res = yield axios.post(
`${config.authURL}/login`,{
headers: {
'Content-Type': 'application/json',{ withCredentials: true })
两个都没有将cookie保存到浏览器cookie中。如何将Set-Cookie值保存到浏览器,以便可以将它们用于身份验证?
解决方法
使用universal-cookie
安装npm
import Cookies from 'universal-cookie';
const cookies = new Cookies();
axios.post(URL,data,{
headers: {
'Content-Type': 'application/json',},{ withCredentials: true }
})
.then((res) => {
let name = res.data.blobName;
let value = res.data.blobValue;
cookies.set(`${name}`,`${value}`);
})
.catch(function (error) {
console.log(error);
});
,
通过withCredentials: true
如下
const res = yield axios.post(
`${config.authURL}/login`,{
headers: { 'Content-Type': 'application/json' },withCredentials: true
}
);
有关更通用的配置,
// You can add it in a separate config file
const request = axios.create({ withCredentials: true });
// While making API call
request.post(`${config.authURL}/login`,{ headers: {...} });
检查here以获得更多详细信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。