Home  >  Article  >  PHP Framework  >  thinkphp5.1 realizes front-end and back-end separation and interaction with php and vue.js

thinkphp5.1 realizes front-end and back-end separation and interaction with php and vue.js

藏色散人
藏色散人forward
2020-11-18 15:44:594943browse

The following is the thinkphp framework tutorial column to introduce you to thinkphp5.1, php, and vue.js to achieve front-end and back-end separation and interaction. I hope it will be useful to friends who need it. help!

The main goal is to use vue.js to transfer the account number and password obtained by the front end to the backend, and then use the tp5.1 framework to obtain the front end value and return token and other values. Then use localStorage.setItem() to store the data in the front end. In subsequent visits, return the value saved by localStorage.setItem() to the background, so that the background can obtain the corresponding value, obtain the value of the database based on this value, and determine whether the value is established. Finally, the successful or failed instruction or The value is returned to the front end. The front end implements an operation or jump based on the obtained value.

1. Preparation work, call vue.js and axios.js in the front-end login.html. Some simple UI uses of Are You Hungry are also called here.

<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>//vue.js的使用
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>//axios的使用

<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>//饿了吗ui js和css的调用。

Detailed use of vue.js and axios.js. For details, please see https://cn.vuejs.org/v2/guide/ vue.js tutorial and https://www.kancloud.cn/yunye/axios/234845

axios.js tutorial. The front-end login.html value passing code is as follows:

<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>

You also need to set up the config configuration file app.php

&#39;default_return_type&#39;    => &#39;json&#39;,

Connect to the database in database.php

The following is the background to obtain data, Perform operations on data. This mainly uses the requests and models of tp5.1, as well as the use of jwt. For details, see https://github.com/firebase/php-jwt

<?php
namespace app\index\controller;//表示放置位置
use think\Controller;//控制器基类
use \Firebase\JWT\JWT;//调用库  jwt 类
use think\Request;//请求对象类
use app\common\model\User 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(&#39;admin&#39;,$admin)->where(&#39;password&#39;,$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(),//生效时间
                &#39;exp&#39; => time() + 3600, //过期时间-10min
                &#39;sub&#39; => $user[&#39;id&#39;],//传递的id值
            );
            
            $jwt = JWT::encode($token, $key);//加密
            //$decoded = JWT::decode($jwt, $key, array(&#39;HS256&#39;));//解密
            return [
                "access_token" => $jwt,//加密数据
                "token_type" => "Bearer",//类别
                "expires_in" => 3600,// 过期时间
            ];//返回数组

        }
        return response()->code(401);//如找不到  返回401指令
    
    }
}

Background User.php obtained according to The data is compared with the database, but when the account password is correct, a string with the unique ID of that account and other data is returned to the front end. The front end saves the value and uses the value to obtain the corresponding data of the user and displays it on the front end. . Same, call those js, and then the js code is as follows:

	<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 route.php receives it and jumps to the middleware to verify the passed value to determine whether to enter the controller. For future operations, use middleware to facilitate future judgments without writing methods on every function of the controller.

Route::rule(&#39;user&#39;,&#39;index/user/show&#39;,&#39;GET&#39;)->middleware(&#39;verify_user&#39;);//路由接收,跳转中间件判断

The middleware VerifyUser.php code is as follows:

<?php

namespace app\http\middleware;//文件位置
use think\Request;//请求
use \Firebase\JWT\JWT;//jwt
use app\common\model\User;//模型
class VerifyUser
{
    public function handle(Request $request, \Closure $next)//使用模型
    {
        $Authorization = $request->header(&#39;Authorization&#39;);//获取前端传递的值
        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 == &#39;Bearer&#39;)//判断$token_type是否正确
        {
            
            try {
                $decoded = JWT::decode($token, $key, array(&#39;HS256&#39;));//解密
                $request->user = $user = User::get($decoded->sub);//获取解密后的用户id
                if(!$user||$decoded->exp<time())//如果id不存在或者时间超出,返回401
                    return response()->code(401);
            }catch(\Exception $e) { //捕获异常,返回401,可能解密失败,$e可返回失败原因
                return response()->code(401);
                }
        }
        else {//$token_type错误也返回401
            return response()->code(401);
        }
        return $next($request);//当没有执行401时,执行到下一个请求,可能有多个中间件或者路由。
    }
        
}

When the middleware is executed, it will jump to the controller User.php

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

At this point, a simple about The front-end and back-end for inputting account and password to log in have been separated, but the code is probably not rigorous enough and needs to be optimized.

The above is the detailed content of thinkphp5.1 realizes front-end and back-end separation and interaction with php and vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete