Home PHP Framework ThinkPHP 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

Nov 18, 2020 pm 03:44 PM
thinkphp5.1 vue.js

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.

1

2

3

4

5

<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的调用。

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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

Copy after login

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

1

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

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

<?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指令

     

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

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

Copy after login

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.

1

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

Copy after login

The middleware VerifyUser.php code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<?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时,执行到下一个请求,可能有多个中间件或者路由。

    }

         

}

Copy after login

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

1

2

3

4

5

public function show(Request $request)//请求,依赖注入

{

   $user = Muser::get($request->user[&#39;id&#39;]);//  模型,获取数据库id相同的表数据,默认表名为Muser的原名 User

   return $user;//返回对应数据

}

Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles