五、Vue:使用axios库进行get和post、用拦截器对请求和响应进行预处理、Mock(数据模拟)
一、axios
【应用】进行请求和传表单
【axios中文档】:https://www.kancloud.cn/yunye/axios/234845
【vue-axios】:https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
【参考】:https://blog.csdn.net/u010132177/article/details/103116767
1.1 安装axios
进入项目目录,运行cmd,运行如下代码:
npm install --save axios
运行项目:
npm run dev
1.2 挂载axios到$axios写法(get)
第一步 src/main.js
【1】引入axios为 Axios
【2】挂载Axios到 $axios (使用其内部函数时:this.$Axios即可)
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios" //【1】引入axios
Vue.prototype.$axios = Axios //【2】挂载Axios到 $axios (使用其内部函数时:this.$Axios即可)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app', //[1]:在index.html里id为#app标签里写入组件内容
  components: { App },//[2]:写入的组件
  template: '<App/>' //[3]:写入的模板名(也可看成一个完整组件)
})
第二步 parent.vue
<template>
  <div class="parent">
    <!-- 【2】把获取到的数据循环展现出来 -->
    <ul>
      <li v-for="v in list">{{v.title}}</li>
    </ul>
    <hr/>【显示获取到的请求】<hr/>
    {{list}}
  </div>
</template>
<script>
  //import axios from 'axios' //首先导入安装好的axios
  export default{
    name:'parent',
    components:{},
    data(){
      return{
        list:[] //定义一个空数组用于存放接收到的数据
      }
    },
    //【1】生命周期函数,组件安装好后调用此函数
    mounted (){
      let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
      this.$axios  //对应main.js里挂载写法
      .get(api)
      .then(res=> {
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    },
    filters:{},
    directives:{},
  }
</script>
<style scoped>
</style>
效果:
【国内首家】微信小程序视频教程免费下载
ionic域资源共享 CORS 详解
移动端触摸滑动js插件_html5手机端轮播插件
未来程序员会被机器人取代吗?
锤子安全锤_锤子真的出了个“锤子”:车充+安全锤
html5能做什么_html5能做哪些开发?
平安口袋银行App采用-Cordova混合开发
JavaScript Emoji 表情库_js 类似于qq微信的表情库
cordova热更新插件-不发布应用市场动态更新APP源码
央行新规!支付宝、微信用户别忘做这件事
HTML5 移动app开发框架该如何选择
纯CSS3动画按钮效果,可用于移动wap app开发
京东每天亏上亿_不会抄袭、剽窃?必将死在互联网下一站的起点上! ...
ionic react-native和native开发移动app那个好
这12行代码分分钟让你电脑崩溃手机重启
罗振宇罗永浩雷军们的演讲 你喜欢哪一个
ionic-native-transitions让你的Ionic应用比原生还快
ionic 1.2.4 发布,最好的html5移动app开发框架
phonegap发布应用到appstore
HTML5仿苹果应用的动画
【显示获取到的请求】
[ { "aid": "499", "catid": "20", "username": "admin", "title": "【国内首家】微信小程序视频教程免费下载", "pic": "portal/201610/13/211832yvlbybpl3rologrr.jpg", "dateline": "1476364740" }, { "aid": "498", "catid": "20", "username": "admin", "title": "ionic域资源共享 CORS 详解", "pic": "", "dateline": "1472952906" }, { "aid": "497", "catid": "20", "username": "admin", "title": "移动端触摸滑动js插件_html5手机端轮播插件", "pic": "portal/201606/28/211604ullzo5arr4iurnum.jpg", "dateline": "1467119820" }, { "aid": "496", "catid": "20", "username": "admin", "title": "未来程序员会被机器人取代吗?", "pic": "portal/201606/02/221818eafffffm4srfdf4s.jpg", "dateline": "1464874140" }, { "aid": "495", "catid": "20", "username": "admin", "title": "锤子安全锤_锤子真的出了个“锤子”:车充+安全锤", "pic": "portal/201605/20/213752f6i56f1e0hbfzhkb.jpg", "dateline": "1463751505" }, { "aid": "494", "catid": "20", "username": "admin", "title": "html5能做什么_html5能做哪些开发?", "pic": "", "dateline": "1463664540" }, { "aid": "493", "catid": "20", "username": "admin", "title": "平安口袋银行App采用-Cordova混合开发", "pic": "", "dateline": "1463294580" }, { "aid": "492", "catid": "20", "username": "admin", "title": "JavaScript Emoji 表情库_js 类似于qq微信的表情库", "pic": "portal/201604/25/084907r2e3im3dvd1q3f7z.jpg", "dateline": "1461545392" }, { "aid": "491", "catid": "20", "username": "admin", "title": "cordova热更新插件-不发布应用市场动态更新APP源码", "pic": "portal/201604/12/152638zaxz5xz3t58bfts2.png", "dateline": "1460446140" }, { "aid": "490", "catid": "20", "username": "admin", "title": "央行新规!支付宝、微信用户别忘做这件事", "pic": "portal/201603/29/144942tcnnenueefagukfk.jpg", "dateline": "1459234206" }, { "aid": "471", "catid": "20", "username": "admin", "title": "HTML5 移动app开发框架该如何选择", "pic": "portal/201511/15/163112q4kz6k2rgcgpi1tc.jpg", "dateline": "1457771160" }, { "aid": "488", "catid": "20", "username": "admin", "title": "纯CSS3动画按钮效果,可用于移动wap app开发", "pic": "portal/201603/09/202742r1kngyt17na7n1nk.jpg", "dateline": "1457526780" }, { "aid": "487", "catid": "20", "username": "admin", "title": "京东每天亏上亿_不会抄袭、剽窃?必将死在互联网下一站的起点上! ...", "pic": "portal/201603/02/155825h28zxs2vsxjccv4c.jpg", "dateline": "1456905746" }, { "aid": "486", "catid": "20", "username": "admin", "title": "ionic react-native和native开发移动app那个好", "pic": "portal/201602/25/193433dtzfvlzl1oavhljy.jpg", "dateline": "1456398960" }, { "aid": "484", "catid": "20", "username": "admin", "title": "这12行代码分分钟让你电脑崩溃手机重启", "pic": "", "dateline": "1453426595" }, { "aid": "483", "catid": "20", "username": "admin", "title": "罗振宇罗永浩雷军们的演讲 你喜欢哪一个", "pic": "", "dateline": "1452226800" }, { "aid": "482", "catid": "20", "username": "admin", "title": "ionic-native-transitions让你的Ionic应用比原生还快", "pic": "portal/201601/07/135529z4r7gwglv4rw8l74.jpeg", "dateline": "1452145500" }, { "aid": "481", "catid": "20", "username": "admin", "title": "ionic 1.2.4 发布,最好的html5移动app开发框架", "pic": "portal/201601/05/132107h9bllr7li74zoh49.jpg", "dateline": "1451971293" }, { "aid": "480", "catid": "20", "username": "admin", "title": "phonegap发布应用到appstore", "pic": "portal/201601/05/122115yhh22i77sqn2ijc6.jpg", "dateline": "1451967910" }, { "aid": "479", "catid": "20", "username": "admin", "title": "HTML5仿苹果应用的动画", "pic": "portal/201601/04/220252ycyddectvivr55pq.png", "dateline": "1451916189" } ]
1.3直接导入到组件axios写法(get)
把main.js里的注释掉
//import Axios from "axios"
//Vue.prototype.$axios = Axios
parent.vue
【0】首先导入安装好的axios
【1】重点:生命周期函数,组件安装好后调用此函数(真正用axios获取数据部分)
【2】把获取到的数据循环展现出来
<template>
  <div class="parent">
    <!-- 【2】把获取到的数据循环展现出来 -->
    <ul>
      <li v-for="v in list">{{v.title}}</li>
    </ul>
    <hr/>【显示获取到的请求】<hr/>
    {{list}}
  </div>
</template>
<script>
  import axios from 'axios' //【0】首先导入安装好的axios
  export default{
    name:'parent',
    components:{},
    data(){
      return{
        list:[] //【0.1】定义一个空数据用来存放接收到的数据
      }
    },
    //【1】生命周期函数,组件安装好后调用此函数
    mounted (){
      let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
      axios
      .get(api)
      .then(res=> {  // 简略写法原:res参数省略了括号.then((res)=>{....})
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    },
    filters:{},
    directives:{},
  }
</script>
<style scoped>
</style>
效果同1.2
1.3.1 把请求参数单独提出来写法(get)
效果同上例
parent.vue 中的请求部分,其它略过
api接口:http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20
//【1】生命周期函数,组件安装好后调用此函数
    mounted (){
      let api="http://www.phonegap100.com/appapi.php";
      let params={a:"getPortalList",catid:20} //【1】把参数提到此处
      this.$axios
      .get(api,{params:params}) //【2】get加上参数
      .then(res=> {
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    }
效果同1.2例
1.3 axios的post
1.3.1post简单写法
//form-data:?name=iwen&age=20
			//x-www-form-urlencoded:{name:"iwen",age:20}
			//注意:axios接受的post请求参数的格式是form-data格式
			import axios from "axios"
			import qs from "qs" //node.js的一个库用于把post之类的参数转换成需要的格式
			axios.post("http://www.wwtliu.com/sxtstu/blueberrypai/login.php",	qs.stringify({
				user_id:"iwen@qq.com",
					password:"iwen123",
					verification_code:"crfvw"
				}))
				.then(res => {
					console.log(res.data)
				})
				.catch(error => {
					console.log(error);
				})
1.3.2使用全局变量axios的post写法
	axios.defaults.baseURL = 'https://api.example.com';
	axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
	axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios"
import qs from "qs"
Vue.prototype.$axios = Axios
Vue.prototype.HOST = '/api'
 Axios.defaults.baseURL = 'http://www.wwtliu.com'; //定义全局变量
 Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
	el: '#app',
	template: '<App/>',
	components: {
		App
	}
})
post.js
<template>
	<div>
		post
	</div>
</template>
<script>
import qs from "qs"  //node.js的一个库,用于对post之类的参数进行转换成需要的类型
export default{
	name:"posts",
	data(){
		return{
		}
	},
	created(){
		var url = this.HOST + "/login";
		console.log(url);
		this.$axios.post(url,	{
			username:"iwen",
			password:"helloiwen"
		})
		.then(res => {
			console.log(res.data)
		})
		.catch(error => {
			console.log(error);
		})
	}
}	
</script>
<style>
</style>
效果:将成功登录对应网站
1.4 拦截器
【作用】:在请求或响应被 then 或 catch 处理前拦截它们。
mian.js
通过拦截器对发送之前数据处理,把格式不对的转化成正确的,在组件中就不用再处理了。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios"
import qs from "qs"
Vue.prototype.$axios = Axios
Vue.prototype.HOST = '/api'
// Axios.defaults.baseURL = 'http://www.wwtliu.com';
// Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.config.productionTip = false
// 添加请求拦截器
Axios.interceptors.request.use(function(config) {
	if (config.method == "post") {//如果请求为post,则把其参数格式进行qs.stringify处理
		config.data = qs.stringify(config.data)
	}
	return config;
}, function(error) {
	// 对请求错误做些什么
	return Promise.reject(error);
});
// 添加响应拦截器
Axios.interceptors.response.use(function(response) {
	return response;
}, function(error) {
	// 对响应错误做点什么
	return Promise.reject(error);
});
/* eslint-disable no-new */
new Vue({
	el: '#app',
	template: '<App/>',
	components: {
		App
	}
})
post.vue
在全局中用拦截器处理数据,在组件中直接用即可,就不用进行处理参数,引用qs.stringfiy(注释部分)处理了
<template>
	<div>
		post
	</div>
</template>
<script>
export default{
	name:"posts",
	data(){
		return{
		}
	},
	created(){
		// var url = this.HOST + "/login";
		// console.log(url);
		// this.$axios.post(url,	{
		// 	username:"iwen",
		// 	password:"helloiwen"
		// })
		// .then(res => {
		// 	console.log(res.data)
		// })
		// .catch(error => {
		// 	console.log(error);
		// })
		var url = this.HOST + "/movie/top250";
		this.$axios.get(url,{
			params:{
				count:10,
				start:0
			}
		})
		.then(res => {
			console.log(res.data)
		})
		.catch(error => {
			console.log(error);
		})
	}
}	
</script>
<style></style>
1.5 跨域解决方案
修改config index.js文件、host文件
【修改完成后,重新运行项目才会生效:(关闭cmd,重新,npm run dev)】
proxyTable: {
	            "/api": {
	                target: "http://localhost:3000",
	                changeOrigin: true,
	                pathRewrite: {
	                    '^/api': ''
	                }
	            }
	        }
添加host
	    	Vue.prototype.HOST = '/api'
	【注意】:此种跨域解决方案,只能适用于测试阶段,打包的时候,不会具备服务器不能跨域了,后端解决。
1.6 Mock:数据模拟
1.自己创建JSON文件。使用get请求形式访问数据
	优点:方便,快捷
	缺点:只能存在get请求
2.项目中集成服务器,模拟各种接口
	优点:模拟真实线上环境
	缺点:增加开发成本
3.直接使用线上数据
	优点:真实
	缺点:不一定每个项目都存在
4.数据模拟库
	www.mockjs.com
	https://github.com/nuysoft/Mock/wiki/Getting-Started五、Vue:使用axios库进行get和post、用拦截器对请求和响应进行预处理、Mock(数据模拟)的更多相关文章
- vue+vuex+axios实现登录、注册页权限拦截
		1.修改config文件夹里的dev.env.js里的BASE_API,把地址改成请求后端的公共部分 1 BASE_API: '"http://192.168.xx.xx"', 2 ... 
- vue 路由拦截器和请求拦截器
		路由拦截器 已路由为导向 router.beforeEach((to,from,next)=>{ if(to.path=='/login' || localStorage.getItem('to ... 
- vue+axois 封装请求+拦截器(请求锁+统一错误)
		需求 封装常用请求 拦截器-请求锁 统一处理错误码 一.封装常用的请求 解决痛点:不要每一个模块的api都还要写get,post,patch请求方法.直接将这些常用的方法封装好. 解决方案:写一个类 ... 
- 第五篇 基于.net搭建热插拔式web框架(拦截器---请求管道)
		好了,前边我们把核心内容介绍完了,接下来要做的就是拦截用户的请求,并把请求转向沙箱内. 这里我们准备通过实现一个HttpModule类来完成请求的拦截与转发.新建一个HuberHttpModule类, ... 
- 细说vue axios登录请求拦截器
		当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的http请求拦截. 1.安装配置axios cn ... 
- VUE 数据请求和响应(axios)
		1. 概述 1.1 简介 axios是一个基于Promise(本机支持ES6 Promise实现) 的HTTP库,用于浏览器和 nodejs 的 HTTP 客户端.具有以下特征: 从浏览器中创建 XM ... 
- vue中Axios的封装和API接口的管理
		前端小白的声明: 这篇文章为转载:主要是为了方便自己查阅学习.如果对原博主造成侵犯,我会立即删除. 转载地址:点击查看 如图,面对一团糟代码的你~~~真的想说,What F~U~C~K!!! 回归正题 ... 
- 前后端数据交互(五)——什么是 axios?
		一.什么是 axios ? axios是基于 Promise 的 ajax 封装库,也是前端目前最流行的 ajax 请求库.简单地说发送 get.post 请求,是一个轻量级的库,使用时可直接引入. ... 
- vue axios请求/响应拦截器
		// main.js中配置 // 引入 axios import Axios from 'axios' // 这时候如果在其它的组件中,是无法使用 axios 命令的. // 但如果将 axios 改 ... 
随机推荐
- 重新学习CSS,认识CSS3中的属性
			之前学css,觉得会改个样式就不错了,直到现在,在做前端开发的时候,才发现自己的前端页面是有多垃圾,而且还不知道该怎么适应各个浏览器,总是很“词穷”,最近是想着好久没去慕课上面了,于是就报着逛一逛的心 ... 
- 用C/C++创建windows服务程序
			转载:https://blog.csdn.net/chenyujing1234/article/details/8023816 一.演示过程下方代码演示了如何使用vs(C/C++)创建windows服 ... 
- Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)B(SET)
			#define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;int a[2007];set<int& ... 
- Centos7 nginx的目录结构与nginx主配置文件解析
			一.nginx的目录结构 [root@node nginx_116]# ls client_body_temp conf fastcgi_temp html logs proxy_temp ... 
- ubuntu14  安装Express及简单应用
			参考资料 [1] 基于Express的Hello World实例 Express 是一个基于 Node.js 平台的极简.灵活的 web 应用开发框架. 1. 环境 工具名 版本 nodejs v11 ... 
- Spring Cloud入门-Nacos实现注册和配置中心(Hoxton版本)
			文章目录 摘要 Nacos简介 使用Nacos作为注册中心 安装并运行Nacos 创建应用注册到Nacos 负载均衡功能 使用Nacos作为配置中心 创建nacos-config-client模块 在 ... 
- 高斯消元几道入门题总结POJ1222&&POJ1681&&POJ1830&&POJ2065&&POJ3185
			最近在搞高斯消元,反正这些题要么是我击败了它们,要么就是这些题把我给击败了.现在高斯消元专题部分还有很多题,先把几道很简单的入门题总结一下吧. 专题:http://acm.hust.edu.cn/vj ... 
- Maven:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
			还是记录使用 maven 时遇到的问题. 一.maven报错 maven package 进行打包时出现了以下报错: Non-resolvable parent POM for com.wpbxin: ... 
- 解决Eclipse Debug 断点调试的source not found问题
			写完代码进行调试的时候,经常会用到断点调试,一步步检测问题,但有时候eclipse有时候无法进入断点,这样就失去了断点的意义,原因是debug无法找到该项目的源代码,解决方法如下 1,打开debug ... 
- u盘装完centos系统恢复
			1.使用windows的cmd窗口,执行diskpart命令 2.执行 list disk命令,查看u盘 3.执行 select disk 2,选中u盘,注意,这里的2是我自己的显示,千万不要选错 4 ... 
