thinkphp5.1和php、vue.js实现前后端分离和交互

下面由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: &#39;#app&#39;,//对应使用id="app"获取信息。 				data() { 					return { 						admin: "", 						password: "", 						dd:"",//定义是三个变量初始化都为空可在id="app"的页面编写{{admin}}返回admin的值 					} 				}, 				methods: {//参数的传递 					login: function () { 						var $this = this; 						console.log("登录触发");//打印返回 						axios({ 						method: &#39;post&#39;, 						url: &#39;http://127.0.0.1/xiangbb/tp5/public/user&#39;, 						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(&#39;token&#39;, response.data.access_token);//本地存储token值 							window.location.href="../index/index.html";//跳转页面 						}) 						.catch(function (error) { 							$this.$message.error(&#39;账号或密码错误!&#39;);//失败,出现错误,返回弹窗 							console.log(error);  						});  					} 				}, 				mounted() {//在模板渲染成html后调用,这里未使用,配套的created在模板渲染成html前调用 					 				} 			}) 		</script>

还需设置config配置文件 app.php

立即学习PHP免费学习笔记(深入)”;

'default_return_type'    =&gt; '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(&#39;post.admin&#39;);         $password=input(&#39;post.password&#39;);//获取前端         $user=db(&#39;user&#39;)->where('admin',$admin)-&gt;where('password',$password)-&gt;find();//删选         //dump($user);         if($user)//使用jwt方法         {             $key = config("app.jwt_key");//key值,唯一保密,在config的app下的jwt_key             $token = array(                 "iss" =&gt; "http://127.0.0.1/xiangbb/tp5/public/user",//  签发地址                 "aud" =&gt; "http://127.0.0.1/xiangbb/qian/login/login.html#",//面向对象地址                 "iat" =&gt; time(),//创建时间                 "nbf" =&gt; time(),//生效时间                 'exp' =&gt; time() + 3600, //过期时间-10min                 'sub' =&gt; $user['id'],//传递的id值             );                          $jwt = JWT::encode($token, $key);//加密             //$decoded = JWT::decode($jwt, $key, array('HS256'));//解密             return [                 "access_token" =&gt; $jwt,//加密数据                 "token_type" =&gt; "Bearer",//类别                 "expires_in" =&gt; 3600,// 过期时间             ];//返回数组          }         return response()-&gt;code(401);//如找不到  返回401指令          } }

后台User.php根据获取的数据跟数据库进行比对,但账号密码正确时,返回一串带有那个账户的唯一id和别的数据返回到前端,前端保存该值,并使用该值获取该用户的相应数据并显示在前端。一样,把那几个js调用,然后js代码如下:

	<script> 		const app = new Vue({ 				el: &#39;#app&#39;, 				data() { 					return { 						 						token: "", 						http: {}, 						} 						 						 					}, 				methods: { 				}, 				created() { 				 					this.token = localStorage.getItem(&#39;token&#39;);//在登录页面验证成功而保存的token值,进行获取 					this.http = axios.create({//整理token的值 							 							baseURL: &#39;http://127.0.0.1/xiangbb/tp5/public/&#39;, 							timeout: 5000, 							headers: {&#39;Authorization&#39;: "Bearer "+this.token} 					}); 					if(!this.token)//若this.token不存在时返回登录页面 					{ 						window.location.href="../login/login.html"; 					} 					else 					{ 						this.http.get(&#39;/user&#39;)//调用上面的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')-&gt;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()-&gt;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-&gt;user = $user = User::get($decoded-&gt;sub);//获取解密后的用户id                 if(!$user||$decoded-&gt;exp<time>code(401);             }catch(Exception $e) { //捕获异常,返回401,可能解密失败,$e可返回失败原因                 return response()-&gt;code(401);                 }         }         else {//$token_type错误也返回401             return response()-&gt;code(401);         }         return $next($request);//当没有执行401时,执行到下一个请求,可能有多个中间件或者路由。     }          }</time>

当中间件执行完,则跳转到控制器User.php

    public function show(Request $request)//请求,依赖注入     {        $user = Muser::get($request-&gt;user['id']);//  模型,获取数据库id相同的表数据,默认表名为Muser的原名 User        return $user;//返回对应数据     }

至此,一个简单的关于账号密码输入登陆的前后端分离制作好了,代码中应该还不够严谨,还需要优化。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享