关于授权 - 离子2中的承载获得POST 401(未授权)错误

时间:2017-10-02 12:14:46

标签: post ionic2

home.ts code

 userdetails()
 {
    // for getting token values
    this.showLoader();
    this.authService.details(this.localStoragekey).then(
        (result) => { 
            this.loading.dismiss();
            this.data = result; 
            console.log('Hello HomePage token details final',this.data);
         }, (err) => { 
            this.loading.dismiss();
            this.presentToast(err); 
        });  
 }

服务提供商代码

details(token) 
{    
    return new Promise((resolve, reject) => {
        let headers = new Headers();  
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', "Bearer" + token );  
        this.http.post(apiUrl+'details', {}, {headers: headers})  
          .subscribe(res => {resolve(res.json());           
        }, 
        (err) => { reject(err); } );
    });  
  }

php laravel code

Route::group(['middleware' => 'auth:api'], function(){
   Route::post('details', 'API\UserController@details');
});

public function details()
{
    $user = Auth::user();
    return response()->json(['success' => $user], $this->successStatus);
}

php代码适用于postman ...但是当我尝试使用离子2时,我遇到了POST http://127.0.0.1:8000/api/details 401(未经授权)错误....

CORS工作正常......

感谢....

1 个答案:

答案 0 :(得分:1)

如Juxture在评论中所述,您的未经授权的错误来自以下行:

headers.append('Authorization', "Bearer" + token );  

这意味着您的Authorization标头如下:

BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

与预期相反:

Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

因此,尝试在Bearer和您的实际令牌之间添加一个空格,然后尝试一下。 如果您在实施JWT时遇到任何其他问题,我建议您查看https://jwt.io/introduction/