五、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 改 ...
随机推荐
- 第二天python
1.pycharm的安装: 1.先去官网下载软件:https://www.jetbrains.com/pycharm/download/#section=windows然后进行下一步,下一步操作既可以 ...
- 第1节 Scala基础语法:14、15、list集合练习
package cn.itcast.collect /** *作业题 */object ListTest { def main(args: Array[String]): Unit = { //创建一 ...
- 【PAT甲级】1006 Sign In and Sign Out (25 分)
题意: 给出学生人数M,输入M组学生ID,到机房的时间,离开机房的时间.输出最早到机房的学生的ID,空格,最后离开机房的学生的ID.(M大小未给出,就用了1e5) AAAAAccepted code: ...
- mysql如何查看表的索引以及如何删除表的索引
mysql中如何查看和删除唯一索引. 查看唯一索引: show index from mytable;//mytable 是表名 查询结果如下: 查询到唯一索引后,如何删除唯一索引呢,使用如下命令: ...
- h5 穿透滚动
引子 h5 页面有弹窗浮层时,浮层之下若产生了滚动,滑动浮层时会让其产生滚动.这是示例页面,移动端访问如下: Origin My GitHub 原因 找到的信息里面有两种说法: 使用了 -webkit ...
- 常见Http状态码大全详解
HTTP状态码的分类 HTTP状态码由三个十进制数字组成,第一个十进制数字定义了状态码的类型,后两个数字没有分类的作用.HTTP状态码共分为5种类型: 具体如下: 状态码 内容 详细内容 信息告知 - ...
- Centos7 nginx的目录结构与nginx主配置文件解析
一.nginx的目录结构 [root@node nginx_116]# ls client_body_temp conf fastcgi_temp html logs proxy_temp ...
- Python使用正则表达式(Regular Expression)超详细
一.导入re库 python使用正则表达式要导入re库. import re在re库中.正则表达式通常被用来检索查找.替换那些符合某个模式(规则)的文本.ps:另外很多人在学习Python的过程中,往 ...
- 01 MATLAB基本概念
基本概念 整数类型 相同整数类型相乘还是整数 整数与浮点数相乘是这种整数类型 不同整数类型不能相乘,除非强制类型转换 整数与整数相乘: >> x = uint32(120); >&g ...
- 用Total Commander替换windos默认资源管理器的方法
Total Commander(简称TC)是一个功能强大的资源管理器. TC本身没有自带的替换windows资源管理器的功能,就必须自己动手解决了. 第一步先Google一下看有没有答案.当时搜出了不 ...