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");//對特定網站訪問開放,不安全
    }
複製代碼
相關文章
相關標籤/搜索