第四章 生命週期函數--35 vue-resource發起get、post、jsonp請求

 vue-resource 官網 https://github.com/pagekit/vue-resourcehtml

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4   <head>
 5     <meta charset="utf-8">
 6     <meta name="viewport" content="width=device-width,initial-scale=1.0">
 7     <title>Document</title>
 8     <!--1.導入Vue的包-->
 9     <script src=" https://cdn.jsdelivr.net/npm/vue"></script>   
10     <!-- 注意:vue-resource依賴與Vue,因此前後順序要注意,先導入vue,再導入vue-resource -->
11     <!-- this.$http.jsonp -->
12     <!-- <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script> -->
13     <script src="./lib/vue-resource-1.5.1.js"></script>
14   </head>
15 
16   <body>
17       <div id="app">
18       <input type="button" value="get請求" @click="getInfo">
19       <input type="button" value="post請求" @click="postInfo">
20       <input type="button" value="jsonp請求" @click="jsonpInfo">
21       </div>
22 
23 
24       <script>
25           //建立 Vue 實例,獲得 ViewModel
26           var vm =  new Vue({
27               el:'#app',
28         data:{
29           msg:''
30         },
31         methods:{
32           getInfo(){//發起get請求
33             //當發起get請求以後,經過then來設置成功的回調函數
34             this.$http.get('http://vue.studyit.io/api/getlunbo').then(function(result){
35               //經過result body 拿到服務器返回的成功的數據
36               // console.log(result)
37             })
38           },
39           postInfo(){//發起post請求
40             //手動發起的Post請求,默認沒有表單格式,因此,有的服務器處理了
41             //經過post方法的第三個參數,{emulateJSON:true}設置提交的內容類型爲普通表單數據格式
42             this.$http.post('http://vue.studyit.io/api/post',{},{emulateJSON:true}).then(result=>{
43               console.log(result.body)
44             })
45           },
46 
47           jsonpInfo(){//發起JSONP請求
48             //箭頭哈數默認就是個匿名函數
49             this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result =>{
50               console.log(result.body)
51             })
52           }
53         }
54           
55           });
56       </script>
57   </body>
58 </html>

 

請求不成功,控制檯輸出:vue

已攔截跨源請求:同源策略禁止讀取位於 http://vue.studyit.io/api/getlunbo 的遠程資源。(緣由:CORS 頭缺乏 'Access-Control-Allow-Origin')。git

未解決github

相關文章
相關標籤/搜索