如有疑問,請在微博 韓峰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()); }
擴展: