下面由thinkphp框架教程欄目給大家介紹thinkphp5.1和php、vue.js實現前后端分離和交互,希望對需要的朋友有所幫助!
主要目標是使用vue.js把前端獲取的賬號和密碼傳到后臺,然后使用tp5.1框架獲取前端的值,并返回token等一些值。然后使用localstorage.setitem()把數據存入前端。在之后的訪問中,把localstorage.setitem()保存的值返回到后臺,使后臺獲取相應的值,并根據這個值獲取數據庫的值,并判斷這個值是否成立,最后把成功或者失敗的指令或者值返回到前端。前端根據獲得的值實現某項操作,或者跳轉。
1.準備工作,在前端login.html調用vue.js和axios.js。這里還調用了餓了嗎的一些簡單ui的使用。
<script></script>//vue.js的使用 <script></script>//axios的使用 <link><script></script>//餓了嗎ui?js和css的調用。
vue.js和axios.js的詳細使用。詳細可看https://cn.vuejs.org/v2/guide/? ?vue.js教程和https://www.kancloud.cn/yunye/axios/234845?
axios.js的教程。前端login.html傳值代碼如下:
<script>//返回信息到前端 const app = new Vue({ el: '#app',//對應使用id="app"獲取信息。 data() { return { admin: "", password: "", dd:"",//定義是三個變量初始化都為空可在id="app"的頁面編寫{{admin}}返回admin的值 } }, methods: {//參數的傳遞 login: function () { var $this = this; console.log("登錄觸發");//打印返回 axios({ method: 'post', url: 'http://127.0.0.1/xiangbb/tp5/public/user', data: { admin: this.admin, password: this.password } })//使用axios根據地址把data的數組值根據post進行傳輸,this.admin和this.password是定義<input v-model="admin">獲取 .then(function (response) {//成功400或401 執行。 //$this.dd = response.data;//獲取后臺數據 //console.log(response.data.access_token); localStorage.setItem('token', response.data.access_token);//本地存儲token值 window.location.href="../index/index.html";//跳轉頁面 }) .catch(function (error) { $this.$message.error('賬號或密碼錯誤!');//失敗,出現錯誤,返回彈窗 console.log(error); }); } }, mounted() {//在模板渲染成html后調用,這里未使用,配套的created在模板渲染成html前調用 } }) </script>
還需設置config配置文件 app.php
立即學習“PHP免費學習筆記(深入)”;
'default_return_type'????=>?'json',
在database.php連接數據庫
下面是后臺獲取數據,對數據進行操作。這里面主要使用了tp5.1的請求和模型,還有就是對jwt的使用,詳細看https://github.com/firebase/php-jwt
<?php namespace appindexcontroller;//表示放置位置 use thinkController;//控制器基類 use FirebaseJWTJWT;//調用庫 jwt 類 use thinkRequest;//請求對象類 use appcommonmodelUser as Muser;//模型 class User extends Controller { public function user() { //echo $_COOKIE["user"];//前端傳參到這里 $admin=input('post.admin'); $password=input('post.password');//獲取前端 $user=db('user')->where('admin',$admin)->where('password',$password)->find();//刪選 ????????//dump($user); ????????if($user)//使用jwt方法 ????????{ ????????????$key?=?config("app.jwt_key");//key值,唯一保密,在config的app下的jwt_key ????????????$token?=?array( ????????????????"iss"?=>?"http://127.0.0.1/xiangbb/tp5/public/user",//??簽發地址 ????????????????"aud"?=>?"http://127.0.0.1/xiangbb/qian/login/login.html#",//面向對象地址 ????????????????"iat"?=>?time(),//創建時間 ????????????????"nbf"?=>?time(),//生效時間 ????????????????'exp'?=>?time()?+?3600,?//過期時間-10min ????????????????'sub'?=>?$user['id'],//傳遞的id值 ????????????); ???????????? ????????????$jwt?=?JWT::encode($token,?$key);//加密 ????????????//$decoded?=?JWT::decode($jwt,?$key,?array('HS256'));//解密 ????????????return?[ ????????????????"access_token"?=>?$jwt,//加密數據 ????????????????"token_type"?=>?"Bearer",//類別 ????????????????"expires_in"?=>?3600,//?過期時間 ????????????];//返回數組 ????????} ????????return?response()->code(401);//如找不到??返回401指令 ???? ????} }
后臺User.php根據獲取的數據跟數據庫進行比對,但賬號密碼正確時,返回一串帶有那個賬戶的唯一id和別的數據返回到前端,前端保存該值,并使用該值獲取該用戶的相應數據并顯示在前端。一樣,把那幾個js調用,然后js代碼如下:
<script> const app = new Vue({ el: '#app', data() { return { token: "", http: {}, } }, methods: { }, created() { this.token = localStorage.getItem('token');//在登錄頁面驗證成功而保存的token值,進行獲取 this.http = axios.create({//整理token的值 baseURL: 'http://127.0.0.1/xiangbb/tp5/public/', timeout: 5000, headers: {'Authorization': "Bearer "+this.token} }); if(!this.token)//若this.token不存在時返回登錄頁面 { window.location.href="../login/login.html"; } else { this.http.get('/user')//調用上面的http,把值傳回后臺 .then(function (response) { console.log(response); }) .catch(function (error) {//token錯誤返回登錄頁面 window.location.href="../login/login.html"; console.log(error); }); } } }) </script>
路由route.php接收,并跳轉到中間件,對傳遞的值進行驗證,以此判斷是否進入控制器,進行以后的操作,使用中間件,方便以后判定不需要在控制器每個函數上都寫上方法。
Route::rule('user','index/user/show','GET')->middleware('verify_user');//路由接收,跳轉中間件判斷
中間件VerifyUser.php代碼如下:
<?php namespace apphttpmiddleware;//文件位置 use thinkRequest;//請求 use FirebaseJWTJWT;//jwt use appcommonmodelUser;//模型 class VerifyUser { public function handle(Request $request, Closure $next)//使用模型 { $Authorization = $request->header('Authorization');//獲取前端傳遞的值 ????????if(!isset($Authorization))?return?response()->code(401);//檢測變量是否存在,不存在返回401 ????????$key?=config("app.jwt_key");//key值?定義在config下的app的jwt_key ????????$token_type?=?explode("?",$Authorization)[0];//根據空格隔開獲取第零個字符串 ????????$token?=?explode("?",$Authorization)[1];//根據空格隔開獲取第一個字符串 ???????? ????????if($token_type?==?'Bearer')//判斷$token_type是否正確 ????????{ ???????????? ????????????try?{ ????????????????$decoded?=?JWT::decode($token,?$key,?array('HS256'));//解密 ????????????????$request->user?=?$user?=?User::get($decoded->sub);//獲取解密后的用戶id ????????????????if(!$user||$decoded->exp<time>code(401); ????????????}catch(Exception?$e)?{?//捕獲異常,返回401,可能解密失敗,$e可返回失敗原因 ????????????????return?response()->code(401); ????????????????} ????????} ????????else?{//$token_type錯誤也返回401 ????????????return?response()->code(401); ????????} ????????return?$next($request);//當沒有執行401時,執行到下一個請求,可能有多個中間件或者路由。 ????} ???????? }</time>
當中間件執行完,則跳轉到控制器User.php
????public?function?show(Request?$request)//請求,依賴注入 ????{ ???????$user?=?Muser::get($request->user['id']);//??模型,獲取數據庫id相同的表數據,默認表名為Muser的原名?User ???????return?$user;//返回對應數據 ????}
至此,一個簡單的關于賬號密碼輸入登陸的前后端分離制作好了,代碼中應該還不夠嚴謹,還需要優化。