第四章 生命周期函数--35 vue-resource发起get、post、jsonp请求

 vue-resource 官网 https://github.com/pagekit/vue-resource

 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>

请求不成功,控制台输出:

已拦截跨源请求:同源策略禁止读取位于 http://vue.studyit.io/api/getlunbo 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。

未解决

原文地址:https://www.cnblogs.com/songsongblue/p/10993845.html