php后台接口跨域处理以及vue实现接口访问

一.前言

组件化开发,先后端的交互方式是接口,在制做接口的时候就要处理好跨域问题,下面我将介绍接口是怎么制做的,怎么处理跨域问题,前端是怎么实现不带参数访问获取数据的,带参数访问获取数据又是怎么实现的php

二.制做接口

我使用的是TP5.1前端

1.修改TP5.1config目录下的database.php文件,进行链接数据库,这里本身看参数配置vue

2.在index控制器中写一个简单的测试方法ios

//测试接口
    public function testinterface() {
       $res= Db::table('user')->select();//获取用户表全部数据
        //dump($res) ;
        $result=["data"=>$res,"status"=>"200","msg"=>"成功获取"];//整理数据

        return json($result);//返回json数据
    }
复制代码

好了,这就是咱们的接口,作好了,如今测试一下,在浏览器中是否能够访问,也就是运行该方法看看可否正常返回数据web

3.浏览器中访问接口ajax

这里说明一下,我已经在phpstudy中配置好了一个新的站点web2.comvue-router

因此我在浏览器的地址栏中输入vue-cli

http://www.web2.com/index.php/index/index/testinterface
复制代码

数据返回正常,说明这个接口时没有问题的数据库

三.前台处理

1.利用vue脚手架vue-cli搭建一个完整的vue项目目录npm

2.安装axios

npm i axios --save
复制代码

2.配置vue路由

修改router目录下的index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
//测试接口
import Testinterface from '@/components/Testinterface'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
    path:'/testinterface',
    name:'Testinterface',
    component:Testinterface
    },
   	]
    }
  ]
})
//暴露路由
export default router
复制代码

3.新建测试组件

components目录下新建Testinterface.vue文件

<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>
复制代码

四.前台测试获取数据

上面后台的接口制做好了,前端请求也写好了,下面测试,在前端可否不带参数访问成功获取数据,执行命令

npm run dev
复制代码

这时页面显示错误,出现了跨域问题,访问获取数据失败

五.后台处理跨域

1.修改index控制器中的测试方法

//测试接口
    public function testinterface() {
       $res= Db::table('user')->select();
        //dump($res) ;
        $result=["data"=>$res,"status"=>"200","msg"=>"成功获取"];
         //处理跨域,添加下面的几句代码
		// 设置响应头
        $headers = [
            'Access-Control-Allow-Origin'=>'*',
            'Access-Control-Allow-Methods'=>'*',
            'Access-Control-Allow-Credentials'=>'false',
            'Access-Control-Allow-Headers'=>'content-type'
        ];		
        return json($result)->header($headers);
    }
复制代码

上面的处理是使用了CORS方案,个人代码中*号表明对全部访问开放,这是不安全的,我这里演示的是简单的处理

2.再次测试能够发现,能够成功访问接口并返回数据

3.下面介绍TP5.1自己提供的处理跨域方法

TP5.1根目录下route目录下的route.php文件中,添加下列代码,为咱们的接口配置路由

Route::get("/testinterface","index/index/testinterface")->allowCrossDomain();
复制代码

修改前端vue请求接口的URL为:

http://www.web2.com/index.php/testinterface
复制代码

以上解决跨域的方法中,第1和第3选择其中一种便可,注意,若是使用配置路由的方式,须要在接口的代码中去掉CORS解决方案的代码

六.访问接口须要传值的状况

上面介绍的是get请求的过程没有传递参数访问接口的状况,可是实际上,咱们在作登陆功能或者其余的需求的时候是须要传值的,下面我就访问接口须要传值的两种请求方式进行介绍,看看是怎么访问的

post请求

1.在index控制器中的写一个testpost方法

public function testpost() {
        $res=['username'=>$_POST['username'],'password'=>$_POST['password']];
        $result=["data"=>$res,"status"=>"200","msg"=>"这些数据由前端传来的"];
        return json($result);
    }
复制代码

2.配置路由

router目录下的index.js文件中,添加一个路由

Route::post("/testpost",'index/index/testpost')->allowCrossDomain();
复制代码

3.在前台安装qs.js

npm i qs --save
复制代码

post方法编码时,须要用qs.js中的方法来处理参数的格式,下面是qs.js中经常使用的两个方法

qs.parse 方法能够把一段格式化的字符串转换为对象格式

qs.stringify是把一个参数对象格式化为一个字符串。

4.修改components目录下Testinterface.vue文件

为何在传递参数时要进行转化,是由于URL自己就是字符串

<template>
    <div>
        hello world
    </div>
</template>
<script>
import axios from 'axios'
//这里注意要引入qs
import qs from 'qs'
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>
复制代码

5.测试访问

执行npm run dev在浏览器中输入http://localhost:8080/#/testinterface

能够看到测试的结果,成功返回数据的咱们传到后台的数据的

get请求

1.在index控制器中的写一个testpost方法

public function testget() {
        $res=['username'=>$_GET['username'],'password'=>$_GET['password']];
        $result=["data"=>$res,"status"=>"200","msg"=>"这些数据由前端传来的"];
        return json($result);
    }
复制代码

2.配置路由

router目录下的index.js文件中,添加一个路由

Route::get("/testget",'index/index/testget')->allowCrossDomain();
复制代码

3.修改components目录下Testinterface.vue文件

get请求中,要注意传递参数的形式

<template>
    <div>
        hello world
    </div>
</template>
<script>
import axios from 'axios'
//这里注意要引入qs
import qs from 'qs'
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>
复制代码

4.测试访问

执行npm run dev在浏览器中输入http://localhost:8080/#/testinterface

能够看到测试的结果,成功返回数据的咱们传到后台的数据的

七.TP5.1中对接口CORS跨域解决进行全局处理

对接口CORS跨域解决进行全局处理并非咱们这篇文章探讨的重点,这只是一个补充的知识点,在TP5.1中制做接口处理跨域问题的最优的解决方案就是配置路由,并使用TP5.1提供的跨域处理方法allowCrossDomain(),那么若是全部的接口在配置路由的时候,都须要添加该方法,代码未免太冗余了

可是若是使用CORS跨域解决方案的话,也一样须要在每个接口中添加CORS方案的代码,也是会形成代码冗余的,那么在TP5.1中能够将CROSS方案的代码写在index控制器的构造函数中,这样,在每执行一个接口以前,都会先执行下列代码

index控制器最开始的位置,添加如下代码

public function __construct() {
        parent::__construct();//调用父类方法,由于这里重写了父类的方法
        //cross方案,用于解决前台ajax跨域请求
        header("Access-Control-Allow-Origin:*");//对全部访问开放,不安全
        //header("Access-Control-Allow-Origin://111.com");//对特定网站访问开放,不安全
    }
复制代码
相关文章
相关标签/搜索