我在我的 laravel 和 vue.js 电子商务项目中使用 laravel 护照进行身份验证。
成功登录后,我想将用户重定向到他/她的仪表板。
这是Vue仪表板页面:
<template>
<div class="content-center">
<h1>Dashboard my account</h1>
<p>
{{userData.name}}
</p>
</div>
</template>
<script>
import Axios from "axios";
export default {
data() {
return {
userData: "",
authToken: ""
}
},
async beforeMount() {
let res = await Axios.get("http://localhost:8000/api/user-details", {
headers: {
Authorization: "Bearer " + this.authToken,
Accept: 'application/json'
},
});
this.userData = res.data;
// let token = await Axios.get("http://localhost:8000/api/user-login")
// this.authToken = res.data.data.auth_token
//let res = await Axios.get("http://localhost:8000/api/user-details");
},
};
</script>
每次登录不同的用户帐户时,我都必须从 Postman 手动复制和粘贴设置 authToken 的值。我想在用户登录时自动设置此令牌。我该怎么做?
这是我的 api 控制器:
class AuthApiController extends Controller
{
public function userDetails(){
return auth()->user();
}
public function login(Request $request){
$user = User::where('email',$request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json([
'success'=>false,
'data'=>[],
'message'=>'Login failed',
'errors'=>[]
]);
}else{
return response()->json([
'success'=>true,
'data'=>['user'=> $user, 'auth_token' => $user->createToken('AuthToken')->accessToken],
'message'=>'Login success',
'errors'=>[]
]);
}
}
更新:
仪表板.vue
<template>
<div class="content-center">
<h1>Dashboard my account</h1>
<p>
{{userData.name}}
</p>
</div>
</template>
<script>
import Axios from "axios";
export default {
data() {
return {
userData: "",
authToken: ""
}
},
async beforeMount() {
let res = await Axios.get("http://localhost:8000/api/user-details", {
headers: {
Authorization: "Bearer " + this.authToken,
Accept: 'application/json'
},
});
this.userData = res.data;
let token = await $api.get("http://localhost:8000/api/user-login")
this.authToken = res.data.data.auth_token
},
};
</script>
图片:
我应该写什么来导入 api.js ?
从 ./../api.js 或 其他任何地方导入 $api ?