马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
第1关:Vue3 Ajax(axios)哀求
任务形貌
本关任务:编写一个能从指定 API 获讽刺话的步伐。
相干知识
为了完成本关任务,你需要把握:
- Vue 与 Ajax;
- axios 哀求的特点;
- 安装 Axios;
- 创建实例的方法;
- axios 实例方法;
- 具体代码演示;
- 实现跨域哀求。
Vue 与 Ajax
Vue 自己是不支持发送 ajax 哀求,需要通过其他库来实现的(比如 vue1.0 版本官方保举的 vue-resource、vue2.0 版本官方保举的 axios),或者也可以利用 jquery 来发送 ajax 哀求。
vue-resource 是 Vue.js 的插件提供了利用 XMLHttpRequest 或 JSONP 进行 Web 哀求和处理相应的服务。 当 vue 更新 到 2.0 之后,作者就宣告不再对 vue-resource 更新,而是保举的 axios,所以发起大家了解一下 vue-resource 就可以。 vue-resource 的 github https://github.com/pagekit/vue-resource。
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中 axios 的 github:https://github.com/axios/axios。
axios 哀求的特点
- 支持 node 端和浏览器端: 同样的 API,node 和浏览器全支持,平台切换无压力;
- 支持利用 Promise 管理异步,告别传统 callback 方式;
- 丰富的配置项: 支持哀求和相应的拦截, 提前处理哀求和相应数据。
安装 Axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
或
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
- 利用 npm: npm install axios
- 直接导入 js 文件
这里我选择去 github,搜索 axios:
官方文档下有非常详细的 API,这里我们就通过直接引入的方式来利用,也就是方法三
创建实例的方法
首先我们来看一个简朴的案例:
- [/code] [list=1]
- [*]// 利用axios
- [*]axios({
- [*]url:"https://api.github.com/users"
- [*]}).then(result => {
- [*]console.log(result);
- [*]})
- [/list] 示例中,我们并没有哀求类型,axios 默认哀求为 get 哀求。
- 如果希望发送 post 等其他方式的 哀求, 可以在配置对象中添加 method 选项
- [b]例如:[/b]
- [code]
复制代码
- // 利用post发送哀求
- axios({
- url:"https://jsonplaceholder.typicode.com/posts",
- method: "post"
- }).then(result => {
- console.log(result);
- })
axios 实例方法
方法作用axios(config)config 是对一些基本信息的配置,比如哀求头,baseURL。axios.request(config)用于发送哀求,默认为 GET 。axios.get(url[, config])用于发送 GET 哀求,一样平常用于查询数据。axios.delete(url[, config])发送一个 DELETE 哀求,一样平常用于删除数据。axios.head(url[, config])用于添加哀求头部信息。axios.options(url[, config])在正式跨域之前,浏览器会根据需要发起一次预检(也就是 option 哀求),用来让服务端返回允许的方法,被跨域访问的 Origin,还有是否需要认证信息等。axios.post(url[, data[, config]])发送一个 POST 哀求,一样平常用于新增数据。data 是作为哀求主体被发送的数据,对应背景中的 body。axios.put(url[, data[, config]])发送一个 PUT 哀求,一样平常用于修改数据。axios.patch(url[, data[, config]]第一个参数是哀求将发送到的 url,第二个参数是您将发送更改的数据。 上面基本的示例中,我们是在 axios() 哀求的配置对象中配置哀求方式,axios 也提供了通过不同的方式发送哀求。
指定了哀求方式发送哀求说明:
- 第一个参数将是发送的 url;
- 第二个参数是哀求的配置对象,可以省略,利用默认配置。
具体代码演示
get 哀求
首先我们写一个 html 代码,按照上面创建 get 实例的方法内容如下:
- [/code] [list=1]
- [*]<!DOCTYPE html>
- [*]<html lang="en">
- [*]<head>
- [*]<meta charset="UTF-8">
- [*]<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
- [*]<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- [*]<title>发送get哀求</title>
- [*]<script>
- [*]window.onload=function(){
- [*]new Vue({
- [*]el:'#app',
- [*]data:{
- [*]users:{
- [*]name:'',
- [*]age:''
- [*]}
- [*]},
- [*]methods:{
- [*]//axios.get的发送参数有两种,两个ajax哀求函数都可实现
- [*]sendGetByStr(){
- [*]//1.get通过直接发字符串拼接
- [*]axios.get(`get.php?name=${this.users.name}&age=${this.users.age}`)
- [*].then(function (response) {
- [*]console.log(response.data);
- [*]})
- [*].catch(function (error) {
- [*]console.log(error);
- [*]});
- [*]
- [*]},
- [*]sendGetByObj(){
- [*]//2.get通过params选项
- [*]axios.get(`get.php?`,{
- [*]params:{
- [*]name:this.users.name,
- [*]age:this.users.age
- [*]}
- [*]})
- [*].then(function (response) {
- [*]console.log(response.data);
- [*]})
- [*].catch(function (error) {
- [*]console.log(error);
- [*]});
- [*]
- [*]}
- [*]}
- [*]});
- [*]}
- [*]
- [*]
- [*]</script>
- [*]</head>
- [*]<body>
- [*]<div id="app">
- [*]<input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
- [*]<input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
- [*]<button @click="sendGetByStr">发送get哀求</button>
- [*]</div>
- [*]
- [*]</body>
- [*]</html>
- [/list] 界面效果如图,为了测试我我们这边就不写样式了:
-
- 然后再写个最简朴的 get.php 文件,相应后输出 get.php
- [code]
复制代码
- <?php
- $name=$_GET["name"];
- $age=$_GET["age"];
- echo "姓名:".$name.","."年龄:".$age;
- ?>
输入名字和年龄,可以直接哀求并输入数据了:
如果出现以下错误:
是由于在浏览器打开本地的 html 文件,上面哀求的模子资源文件是一个本地文件,协议是 file://,出于安全性考虑,Chrome 默认禁止了这种用法,file 协议和 http/https 协议不同,会被 Chrome 认为是跨域访问,所以会报被 CORS(Cross-Origin Resource Sharing,跨域资源共享)的安全策略制止。
办理方法 以谷歌浏览器为例:
- 找到你谷歌浏览器浏览器安装的位置,一样平常默认安装的位置 C:\Program Files\Google\Chrome\Application;
- 在该目次打开命令行,直接在文件夹导航栏输入 cmd,敲回车,回车之后就进入了 cmd 命令行;
- 输入命令 chrome.exe --disable-web-security --user-data-dir=C:\MyChromeUserFata。
这个时间谷歌浏览器会重新打开一个窗口,然后把你本地 html 文件放到浏览器中就好了。
post 哀求
同样写一个按照创建 post 的实例方法,写一个 post.html 代码文件:
- [/code] [list=1]
- [*]<!DOCTYPE html>
- [*]<html lang="en">
- [*]<head>
- [*]<meta charset="UTF-8">
- [*]<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
- [*]<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- [*]<title>发送post哀求</title>
- [*]<script>
- [*]window.onload=function(){
- [*]new Vue({
- [*]el:'#app',
- [*]data:{
- [*]users:{
- [*]name:'',
- [*]age:''
- [*]}
- [*]},
- [*]methods:{
- [*]sendPsot(){
- [*]axios.post('post.php', {
- [*]name: this.users.name,
- [*]age: this.users.age,
- [*]})
- [*].then(function (response) {
- [*]console.log(response);
- [*]})
- [*].catch(function (error) {
- [*]console.log(error);
- [*]});
- [*]}
- [*]
- [*]}
- [*]});
- [*]}
- [*]
- [*]
- [*]</script>
- [*]</head>
- [*]<body>
- [*]<div id="app">
- [*]<input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
- [*]<input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
- [*]<button @click="sendPsot">发送post哀求</button>
- [*]</div>
- [*]
- [*]</body>
- [*]</html>
- [/list] 另外也同样的加上 post.php 代码文件:
- [code]
复制代码
- <?php
- $name=$_POST["name"];
- $age=$_POST["age"];
- echo "姓名:".$name.","."年龄:".$age
- ?>


大家大概会发现有点异常,由于我们并没有获取到对应的 name 以及 age,这是由于这种方式通报的数据是 Request Payload,所以我们要轻微修改一下 html 文件:
- [/code] [list=1]
- [*]<!DOCTYPE html>
- [*]<html lang="en">
- [*]<head>
- [*]<meta charset="UTF-8">
- [*]<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
- [*]<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- [*]<title>发送post哀求</title>
- [*]<script>
- [*]window.onload=function(){
- [*]new Vue({
- [*]el:'#app',
- [*]data:{
- [*]users:{
- [*]name:'',
- [*]age:''
- [*]}
- [*]},
- [*]methods:{
- [*]sendPsot(){
- [*]axios.post('post.php',this.users,{
- [*]//transformRequest就是用来处理转换的
- [*]transformRequest:[
- [*]function(data){
- [*]let transObj='';
- [*]for(let i in data){
- [*]transObj+=i+'='+data[i]+'&';
- [*]}
- [*]return transObj;
- [*]}
- [*]]
- [*]})
- [*].then(function (response) {
- [*]console.log(response.data);
- [*]})
- [*].catch(function (error) {
- [*]console.log(error);
- [*]});
- [*]}
- [*]
- [*]}
- [*]});
- [*]}
- [*]
- [*]
- [*]</script>
- [*]</head>
- [*]<body>
- [*]<div id="app">
- [*]<input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
- [*]<input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
- [*]<button @click="sendPsot">发送post哀求</button>
- [*]</div>
- [*]
- [*]</body>
- [*]</html>
- [/list] 末告终果如下:
-
- [align=center][img=325,242]https://i-blog.csdnimg.cn/blog_migrate/3a84afefe91e2145bf9b130e5622aa2f.png[/img][/align]
- [size=2]实现跨域哀求[/size]
- 上面都是在没有跨域的情况下进行 ajax 哀求的,如果我们要跨域哀求呢? 跨域哀求的话 axios 还没有办理方案,当时,可以通过 vue-resource 的 jonsp 来实现>
- 接下来就利用 vue-resource 跨域哀求写一个获取 github 账户信息的例子,API链接 :
- [code]
复制代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
- <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
- <title>输入用户名获取github上的账户信息</title>
- <script>
- window.onload=function(){
- new Vue({
- el:'#app',
- data:{
- id:'',
- userData:''
- },
- methods:{
- getData(){
- this.$http.jsonp(`https://api.github.com/users/${this.id}`).then(function(resp){
- this.userData=resp.data.data;
- });
- }
- }
- });
- }
- </script>
- </head>
- <body>
- <div id="app">
- <input type="text" v-model="id" placeholder="姓名">
- <button @click="getData">获取github的账户信息</button>
- <div v-for="(v,k) in userData">{{k}}:{{v}}</div>
- </div>
- </body>
- </html>
这个典型的跨域哀求例子输入姓名即可查询在 github 上面的信息,大家也可以自行改进。
编程要求
根据提示,在右侧编辑器补充代码,采用指定接口获取到“笑话”内容即可。
测试说明
平台会对你编写的代码进行测试,具体的运行效果图如下:
预期输出:
- [/code] [list=1]
- [*]Vue 服 务 启 动 成 功
- [*]Vue3 axios 设 计 完 成
- [/list] [hr] 开始你的任务吧,祝你成功!
- [size=3]代码文件[/size]
- [code]<!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <!-- 官网提供axios在线地址 -->
- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
- <title>axios+vue</title>
- </head>
- <body>
- <div id="app">
- <button @click="getJoke">获取笑话</button>
- <p> {{joke}} </p>
- </div>
- <script>
- /*
- 接口:随机获取一条笑话
- 请求地址:https://autumnfish.cn/api/joke
- 请求方法:get
- 请求参数:无
- 响应内容:随机笑
- */
- var app = new Vue({
- el: "#app",
- data: {
- joke: "一个很好笑的笑话"
- },
- methods: {
- getJoke: function() {
- var that = this;
- axios.get('https://autumnfish.cn/api/joke')
- .then(function(response) {
- that.joke = response.data;
- })
- .catch(function(error) {
- console.log(error);
- });
- }
- },
- })
- </script>
- </body>
- </html>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |