A preface.

Componentized development, front and back end interaction is interface, in the production of interface to deal with cross-domain problems, I will introduce how to make the interface, how to deal with cross-domain problems, how to achieve the front-end access without parameters to obtain data, access with parameters to obtain data is how to achieve

Two. Make interfaces

I use TP5.1

1. Modify the database. PHP file in the config directory of TP5.1 to connect to the database

2. Write a simple test in the Index controller

    // Test the interface
    public function testinterface(a)
    {
       $res= Db::table('user')->select();// Get all data from the user table
        //dump($res) ;
        $result=["data"=>$res,"status"= >"200"."msg"= >"Successful acquisition"];// Collate data

        return json($result);// Returns json data
    }
Copy the code

Ok, so that’s our interface, that’s done, and now let’s test if it’s accessible in the browser, so let’s run this method and see if it returns data

3. Access interfaces in the browser

For the record, I have configured a new site, web2.com, in PHPStudy

So I typed it in the browser’s address bar

http://www.web2.com/index.php/index/index/testinterface
Copy the code

The data returned to normal, indicating that there is no problem with this interface

Three. Reception processing

1. Use VUE scaffolding VUE – CLI to build a complete VUE project directory

2. Install axios

npm i axios --save
Copy the code

2. Configure vUE routes

Change the index.js file in the router directory

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
// Test the interface
import Testinterface from '@/components/Testinterface'

Vue.use(Router)

let router = new Router({
  routes: [{path: '/'.name: 'HelloWorld'.component: HelloWorld
    },
    {
    path:'/testinterface'.name:'Testinterface'.component:Testinterface
    },
   	]
    }
  ]
})
// Expose the route
export default router
Copy the code

3. Create a test component

Create a new testInterface. vue file in the Components directory

<template>
    <div>
        hello world
    </div>
</template>
<script>
import axios from 'axios'
export default {
    created(){
        this.getdata();
    },
    methods:{
        getdata(){
            axios.get('http://www.web2.com/index.php/index/index/testinterface').then((data)=>{
                console.log(data);
            });
        } 
    }
}
</script>
<style lang="">
    
</style>
Copy the code

4. Front desk test to obtain data

The above background interface is made good, the front end request is also written, the following test, in the front end can access data without parameters successfully, execute the command

npm run dev
Copy the code

At this time, the page display error, cross-domain problems occur, access to obtain data failure

Five. Background processing across domains

1. Modify the test method of the INDEX controller

    // Test the interface
    public function testinterface(a)
    {
       $res= Db::table('user')->select();
        //dump($res) ;
        $result=["data"=>$res,"status"= >"200"."msg"= >"Successful acquisition"];
         // To handle cross-domain, add the following lines of code
		// Set the response header
        $headers = [
            'Access-Control-Allow-Origin'= >The '*'.'Access-Control-Allow-Methods'= >The '*'.'Access-Control-Allow-Credentials'= >'false'.'Access-Control-Allow-Headers'= >'content-type'
        ];		
        return json($result)->header($headers);
    }
Copy the code

The above processing is using the CORS scheme, my code in the asterisk stands for open to all access, this is not secure, I demonstrate here is simple processing

2. The interface can be accessed successfully and data can be returned

3. The following describes the cross-domain processing methods provided by TP5.1 itself

Add the following code to the route.php file in the route directory of TP5.1 root directory to configure the route for our interface

Route::get("/testinterface"."index/index/testinterface")->allowCrossDomain();
Copy the code

Change the URL of the front-end VUE request interface to:

http://www.web2.com/index.php/testinterface
Copy the code

Choose one of the first and third ways to solve the cross-domain problem. Note that if you use the route configuration method, you need to remove the CORS solution code from the interface code

The case that the interface needs to pass the value

The above introduction is the process of get request does not pass parameters to access the interface situation, but in fact, we do login function or other requirements are needed to pass the value, the following I will access the interface need to pass the value of the two request methods to introduce, see how to access

A post request

1. Write a testPost method in the Index controller

    public function testpost(a)
    {
        $res=['username'=>$_POST['username'].'password'=>$_POST['password']];
        $result=["data"=>$res,"status"= >"200"."msg"= >"This data is coming from the front end."];
        return json($result);
    }
Copy the code

2. Configure routes

Add a route to the index.js file in the router directory

Route::post("/testpost".'index/index/testpost')->allowCrossDomain();
Copy the code

3. Install qs.js in the foreground

npm i qs --save
Copy the code

When encoding the POST method, you need to use the methods in Qs.js to handle the format of the parameters. The following two methods are commonly used in Qs.js

The qs.parse method converts a formatted string to an object format

Qs. stringify formats a parameter object into a string.

4. Modify the Testinterface. Vue file in the Components directory

Why do we convert when we pass parameters, because the URL itself is a string

<template> <div> hello world </div> </template> <script> import axios from 'axios' export default { created(){ this.getdata(); }, methods:{ getdata(){ axios.post('http://www.web2.com/index.php/testpost',qs.stringify({username:'test',password:'123'}))  .then((data)=>{ console.log(data); }); } } } </script> <style lang=""> </style>Copy the code

5. Test access

Run NPM run dev and enter http://localhost:8080/#/testinterface in the browser

You can see the results of the test, the successful return of the data that we sent to the background

A get request

1. Write a testPost method in the Index controller

    public function testget(a)
    {
        $res=['username'=>$_GET['username'].'password'=>$_GET['password']];
        $result=["data"=>$res,"status"= >"200"."msg"= >"This data is coming from the front end."];
        return json($result);
    }
Copy the code

2. Configure routes

Add a route to the index.js file in the router directory

Route::get("/testget".'index/index/testget')->allowCrossDomain();
Copy the code

3. Modify the Testinterface. Vue file in the Components directory

In get requests, pay attention to the form in which the parameters are passed

<template> <div> hello world </div> </template> <script> import axios from 'axios' export default { created(){ this.getdata(); }, methods:{ getdata(){ axios.get('http://www.web2.com/index.php/testget',{ params:{ 'username':'testget', 'password':123456 } }).then((data)=>{ console.log(data); }); } } } </script> <style lang=""> </style>Copy the code

4. Test access

Run NPM run dev and enter http://localhost:8080/#/testinterface in the browser

You can see the results of the test, the successful return of the data that we sent to the background

Seven.TP5.1In the interfaceCORSCross-domain resolution for global processing

The global processing of interface CORS cross-domain solution is not the focus of this article, which is just a supplementary knowledge point. In TP5.1, the optimal solution to make interface to deal with cross-domain problem is to configure routing, and use the cross-domain processing method provided by TP5.1 allowCrossDomain(), then if all the connections Interface in the configuration of routing, need to add this method, the code is too redundant

However, if the CORS cross-domain solution is used, the code of CORS scheme also needs to be added to each interface, which will also cause code redundancy. In TP5.1, the code of CROSS scheme can be written in the constructor of index controller, so that before each interface is executed, the following code will be executed

At the beginning of the Index controller, add the following code

    public function __construct(a)
    {
        parent::__construct();// Call the superclass method because it overrides the superclass method
        // Cross solution for foreground Ajax cross-domain requests
        header("Access-Control-Allow-Origin:*");// Open to all access, not secure
        //header("Access-Control-Allow-Origin://111.com"); // Open to specific web access, not secure
    }
Copy the code