Larvel 5.4,Passport和Angular 7不能很好地配合玩耍

时间:2019-01-01 15:56:25

标签: php angular laravel laravel-passport

我有一个使用Laravel 5.4构建的网站,我正在该网站上更新UI。我想朝着使用Angular 7的单页应用程序发展。但是,我一直试图向我的API端点发出请求,但我一直遇到401错误。我已按照此处的说明进行操作:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript将meta标签添加到页面,进行了附加设置,并像这样开始使用Angulars HTTP库

this.httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': this.meta.getTag('name=csrf-token').content
    })
};

this.http.get('api/v1/people', this.httpOptions).subscribe((data: any) => {console.log(data); });

但是我继续收到401错误。此外,还有Kernel.php

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,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
    ],

    'api' => [
        'throttle:60,1',
        'auth:api'
    ],
];

和Routes.php

Route::group(['middleware' => 'auth:api'], function(){
   Route::group(['prefix' => 'api/v1'], function () {
     Route::get('people', 'personController@apiIndex');
     Route::get('person/{id}', 'personController@apiGetPerson');
     Route::post('contactevent', 'contactEventsController@apiAddContactEvent');
   });
});

任何输入将不胜感激。

1 个答案:

答案 0 :(得分:0)

好像我误解了所提供的一些文档。当您想通过在网站上投放的JavaScript使用api时,无需在auth:api组中包含路由即可对呼叫进行身份验证。 Laravel会随您的请求传递一个cookie,此外,除非它是POST请求,否则不需要CSRF。我的解决方案是将路由转移到auth中间件组,如下所示:

Route::group(['middleware' => 'auth'], function () {
  Route::get('api/v1/people', 'personController@apiIndex');
}

然后像这样重写我的Angular HTTP请求:

this.httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json'
    })
};

this.http.get('api/v1/people', this.httpOptions).subscribe((data: any) => {console.log(data); });

一切都按预期进行。