dougu6815 2016-05-14 21:10
浏览 47

访问通过Laravel中的Ajax登录用户

I have read a lot about this but I can't seem to solve it, so I am just going around in circles. I am trying to access a logged user via an API route I have setup using;

$user = Auth:user();

The problem is; $user is always null when I make an ajax request but the user is not null when I access the API route in the browser. For example entering; api.example.com/v1/myaccount

I have solved many problems along the way such as turning on sessions for all subdomains and adding the following to the api route middleware.

    protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];

Previously the url was returning a 404 error via Ajax but worked fine in the browser. Now the $user variable is just empty as if no user is logged. But I have logged normally.

I am using Laravel 5.2

  • 写回答

2条回答 默认 最新

  • douan7601 2016-05-14 21:25
    关注

    Where are you Ajax routes pointing to? I do this a lot and never have issues so ill share the way i do it.

    My Ajax requests look something like this:

    (Note: ajaxSetup is mandatory)

    $.ajaxSetup( {
        headers: {
          'X-CSRF-Token': $( 'meta[name=_token]' ).attr( 'content' )
        }
      } );
    
      $('#ID').change(function(){
    
          $.ajax({
            type: 'post',
            url: '/super/cool/route',
            data: { stuff : stuff},
            success: function(data) {
    
    
            }
          })
        }
      });
    

    And the route will point to a controller.

    I think the problem for you is that you are not including the "Auth" in the top of the file. On each controller you see:

    use Auth;
    

    Check and make sure that is where the ajax routes are pointing to.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!