vue-axios跨域请求实例(根据用户ID获取github账户信息)

获取指定github账户信息并显示

一、需求分析

需求分析:github和自己的项目不在一个域里面,需要跨域查询。

跨域常见有两种实现方式:

  • 一是JSONP(客户端)
  • 二是CORS(服务端)

跨域的实现原则:

  • 如果某网站的服务端是允许跨域的,客户端直接请求即可。
  • 如果某网站的服务端不允许跨域,则需要使用JSONP来实现跨域。

github的服务端是允许跨域的,因此直接获取账号信息。

 

二、需求实现

 html页面代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>获取github账户信息</title>
 6 <!--  引入vue-->
 7   <script src="../js/vue.js"></script>
 8   <script src="../js/axios.min.js"></script>
 9   <script>
10     window.onload=function(){
11       new Vue({
12         el:'#hello',
13         //data用来存储数据
14         data:{
15           uid:'',
16           user:{
17             name:'',
18             avatar_url:''
19           }
20         },
21         //methods用来存储方法
22         methods:{
23          getUserByID(){
24           axios.get('https://api/github.com/users/${uid}')
25           .then(res=>{
26             console.log('获取github用户信息成功',res)
27             this.user = res.data
28           }).catch(err=>{
29             console.log('获取github用户信息失败',err)
30           });
31          }
32         },
33       })
34     }
35   </script>
36 </head>
37 <body>
38 <div id="hello">
39   githubID:<input type="text">
40   <button @click='getUserByID(uid)'>获取指定github账户信息</button>
41   <br>
42   姓名:{{user.name}}
43   <br>
44   头像<img :src="user.avatar_url" alt="">
45 </div>
46 </body>
47 </html>

 

posted @ 2021-08-25 15:21  AnnLing  阅读(544)  评论(0)    收藏  举报