【发布时间】:2019-11-05 20:52:07
【问题描述】:
我正在开发移动应用程序,现在每次我尝试执行需要用户身份验证的操作时,我都会通过 API 将我的应用程序连接到服务器,我收到 401 错误,而与 postman 相同的操作可以毫无问题地完成工作。
我做了什么
- 将令牌存储到设备本地存储中
- 检索到该令牌并将其作为请求标头发送到服务器
- 额外添加
'Accept': 'application/json, text/plain',到标头请求 - 添加了 this package 以打开我的后端 CROS 源。
代码
app
logout() {
const headers = new HttpHeaders({
'Accept': 'application/json, text/plain',
'Authorization': this.token["token_type"] + " " + this.token["access_token"]
});
return this.http.post(this.env.BASE_URL + '/logout', { headers: headers })
.pipe(
tap(data => {
this.storage.remove("token");
this.isLoggedIn = false;
delete this.token;
return data;
})
)
}
route (back-end)
Route::group(['middleware' => 'auth:api'], function(){
Route::post('logout', 'Api\AuthController@logout');
});
controller (back-end)
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
对于这个示例,我分享了我的注销方法以及其他方法,例如 update、delete、store 是同一个结构。
结果
有什么想法吗?
【问题讨论】:
-
我在您的请求标头中看不到授权标头。在随附的屏幕截图中。
-
@skdroid 但我的代码中有它
'/logout', { headers: headers }你认为哪里出了问题? -
代码是否正确可能是它的授权标头问题,您是否添加了
Bearer与B 大写? -
您正在使用没有正文的发布请求。试试
return this.http.post(this.env.BASE_URL + '/logout', null, { headers: headers })。我宁愿为此目的使用获取请求。 -
@mafortis 您找到解决问题的方法了吗?
标签: angular laravel ionic-framework