【发布时间】:2021-10-21 10:54:48
【问题描述】:
我正在尝试将数组作为 json 保存在 cookie 中,在前端有一个被填充的表单,它每隔几分钟自动保存一次我想将数据保存为 JSON 格式cookie,以防用户离开页面。
在控制器中,我像这样保存 cookie:
public function autoSave() {
$data = request()->validate([
'data' => 'required'
]);
$lifetime = time() + 60 * 60 * 24 * 365;// one year
$array = json_encode($data);
Cookie::forget('listData'); //I use this to delete the old cookie and generate a new one
$cookie = Cookie::make('listData', $array, $lifetime);
return response()->json(['success' => true])->withCookie($cookie);
}
我这样检索它:
public function getAutoSave() {
if(Cookie::get('listData') !== null) {
$data = Cookie::get('listData');
$data = json_decode($data);
return response()->json([
'data' => $data
]);
}
else {
return response()->json([
'data' => false
]);
}
}
自动保存有时有效,有时无效,可能是什么问题?
**编辑
查看服务器响应我收到错误The Set-Cookie header had invalid syntax,可能是我尝试保存为 cookie 的 JSON 因为它太长而创建了它。
【问题讨论】:
标签: laravel vue.js cookies axios