Laravel 5.4用户Null使用React Fetch

问题描述 投票:1回答:1

路线(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:

enter image description here

是什么阻止用户会话工作?几个小时一直搞乱这个。

php laravel reactjs
1个回答
0
投票

刚刚注意到我的图片显示cookie被退回,而不是发送。

fetch()代码更改为此并且有效:

    fetch('/user',{
        credentials: 'include' //Includes cookies
    })
        .then(response => {
            return response.json();
        })
        .then(json => {
            console.log(json);
        });
© www.soinside.com 2019 - 2024. All rights reserved.