Cookies.get() 返回未定义
2023-01-28
1714
我正在使用
js-cookie
包在我的 React 应用中存储和处理 cookie。cookie 在用户首次登录时设置,并在浏览器的“应用程序”选项卡中可见。我创建了一个将新产品添加到数据库的服务,cookie 存储 jwt 令牌,然后在用户执行任何操作之前将其传递到后端进行验证。Cookies.get() 方法在此服务中始终返回未定义。
这里是服务的代码
import axios from 'axios'
import Cookies from "js-cookie";
import { ProductTypes } from '../domain/entities/Product';
import { addProductResponse, getProductResponse } from '../domain/responses/productResponse';
const token = Cookies.get("authToken");
const instance = axios.create({
baseURL: 'http://localhost:8000/',
headers: {
"Content-type": "application/json",
"Authorization":`Bearer ${token}`
},
});
export const addProduct = async(formValues:ProductTypes):Promise<addProductResponse>=>{
console.log("token from react",token);
return await instance.post(`/products/create-product`,formValues).then(
(response:addProductResponse) => response)
}
这是它的设置方式
const setToken = (authToken: string) => {
Cookies.set("authToken", authToken, {
expires: new Date(Date.now() + 15 * 60 * 1000),
secure: true,
});
};
有人可以指出我可能做错了什么吗? PS:这是一个 Typescript 应用程序
1个回答
其实,你在
Cookies.set
函数中添加了
secure: true
参数,并且调用了
baseURL: 'http://localhost:8000/'
,但没有使用
HTTPS
协议,这就是原因。因此,你只需设置
secure: false
The Secure attribute limits the scope of the cookie to "secure" channels (where "secure" is defined by the user agent). When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS) [RFC2818]).
Fedor Petrov
2023-01-28