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


如有疑問,請在微博 韓峰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 初始化時如何配置默認訪問某個文件?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM