路线(web.php)
Route::get('user', function () {
$user=Auth::user();
return response(['user_id'=>$user->id],200);
});
React.js fetch()
fetch('/user')
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
});
在浏览器中访问/user
时:
{"user_id":1}
运行fetch()
方法时:
Trying to get property of non-object
这是因为$user=Auth::user();
正在返回null
。
我知道这不是一个csrf
问题,因为返回静态内容(如user_id=>1
)可以正常使用fetch方法。
以下是随请求发送的cookie:
是什么阻止用户会话工作?几个小时一直搞乱这个。
刚刚注意到我的图片显示cookie被退回,而不是发送。
将fetch()
代码更改为此并且有效:
fetch('/user',{
credentials: 'include' //Includes cookies
})
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
});