vue webpack-simple配合TP5.1本地環境開發之跨域訪問

php代碼,返回提交的數據

    public function message()
    {
        $data=Request::param();
        return json_encode($data);
    }

vue init webpack-simple

1、簡單模板中,用axios的get方法,可以直接跨域訪問。

mounted(){    //加載完成時
  console.log(this.$root.host);//獲取主函數中的host屬性,裏面存放的域名
    this.axios.get(this.$root.host+'/index/message',{
      params:{
        id:'123',
        name:'456'
      }
      }).then(function(res){
        console.log(res);
      }).catch(function(error){
        console.log(error);
      });
    },

傳值成功。

2、簡單模板中,用axios的post方法,需要先在create中將數據進行轉換纔可以跨域訪問。

        mounted(){
            console.log(this.$root.host);//域名在main.js中存放
            var server=this.axios.create({
                transformRequest: [//對數據轉換成類似get傳參的模式
                    data => {
                        data=qs.stringify(data);
                        console.log(data);
                        return data;
                    }
                ]
            })
            server.post(this.$root.host+'/index/message',{
                    id:'123',
                    name:'456'
            })
            .then(function(res){
                console.log(res);
            }).catch(function(error){
                console.log(error);
            });
        }

傳值成功。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章