1. 程式人生 > >Yii + Vue 前後端交互(跨域)

Yii + Vue 前後端交互(跨域)

啟動服務 log ont 9.png resp .get 按鈕 成功 source

如有疑問,請在微博 韓峰26 留言!

前端配置什麽指明發送到具體的URL

  需要使用vue-resource:

  下載:    

    cd 項目根目錄
    npm install vue-resource --save-dev

  項目結構:

    技術分享

  配置:

    1.在main.js引入

      import VueResource from ‘vue-resource‘

      Vue.use(VueResource)

    技術分享

    2.在發送請求.vue文件調用

                    test (){                          
                          
this.$http.get(‘http://localhost:8080/home/site/test‘).then(function (response) { // 響應成功回調 console.log(response); console.log(‘ss‘) }, function (response) { // 響應錯誤回調 console.log(response) console.log(
‘failed‘) }); }

    技術分享    

    3.在該.vue文件中添加測試按鈕button,調用test方法,在頁面點擊測試

      <button @click=‘test‘>點擊</button>

後端配置(yii):

  項目配置:

  技術分享

  1.需要指明哪個URL可以訪問後端的某個controller, 如果所有URL都能訪問, 使用*代替

   在該controller中添加     

            public function
behaviors() { return ArrayHelper::merge([ [ ‘class‘ => Cors::className(), ‘cors‘ => [ //‘Origin‘ => [‘http://localhost:1024‘], ‘Origin‘ => [‘*‘], ‘Access-Control-Request-Method‘ => [‘POST‘], ‘Access-Control-Allow-Credentials‘ => true, ], ], ], parent::behaviors()); }

技術分享

  2.在controller中添加被調用的方法:

                public function actionTest(){
                    return ‘test‘;
                }        

啟動服務器就可以在vue頁面點擊button訪問yii了。

註: 很多情況不能運行是訪問後端controller下的action方法路徑寫錯,先使用get方法測試,路徑一定要寫對!不然報500錯誤

若報錯No ‘Access-Control-Allow-Origin‘ header is present on....,需要在後端該controller裏申明

‘Origin‘ => [‘http://localhost:1024‘] (或者‘Origin‘ => [‘*‘])  

            public function behaviors()
            {
                return ArrayHelper::merge([
                    [
                        ‘class‘ => Cors::className(),
                        ‘cors‘ => [
                            ‘Origin‘ => [‘*‘],
                            ‘Access-Control-Request-Method‘ => [‘POST‘],
                            ‘Access-Control-Allow-Credentials‘ => true,
                        ],
                    ],
                ], parent::behaviors());
            }

擴展:

  yii 初始化時如何配置默認訪問某個文件?

Yii + Vue 前後端交互(跨域)