一、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(数据模拟)的更多相关文章

  1. vue+vuex+axios实现登录、注册页权限拦截

    1.修改config文件夹里的dev.env.js里的BASE_API,把地址改成请求后端的公共部分 1 BASE_API: '"http://192.168.xx.xx"', 2 ...

  2. vue 路由拦截器和请求拦截器

    路由拦截器 已路由为导向 router.beforeEach((to,from,next)=>{ if(to.path=='/login' || localStorage.getItem('to ...

  3. vue+axois 封装请求+拦截器(请求锁+统一错误)

     需求 封装常用请求 拦截器-请求锁 统一处理错误码 一.封装常用的请求 解决痛点:不要每一个模块的api都还要写get,post,patch请求方法.直接将这些常用的方法封装好. 解决方案:写一个类 ...

  4. 第五篇 基于.net搭建热插拔式web框架(拦截器---请求管道)

    好了,前边我们把核心内容介绍完了,接下来要做的就是拦截用户的请求,并把请求转向沙箱内. 这里我们准备通过实现一个HttpModule类来完成请求的拦截与转发.新建一个HuberHttpModule类, ...

  5. 细说vue axios登录请求拦截器

    当我们在做接口请求时,比如判断登录超时时候,通常是接口返回一个特定的错误码,那如果我们每个接口都去判断一个耗时耗力,这个时候我们可以用拦截器去进行统一的http请求拦截. 1.安装配置axios cn ...

  6. VUE 数据请求和响应(axios)

    1. 概述 1.1 简介 axios是一个基于Promise(本机支持ES6 Promise实现) 的HTTP库,用于浏览器和 nodejs 的 HTTP 客户端.具有以下特征: 从浏览器中创建 XM ...

  7. vue中Axios的封装和API接口的管理

    前端小白的声明: 这篇文章为转载:主要是为了方便自己查阅学习.如果对原博主造成侵犯,我会立即删除. 转载地址:点击查看 如图,面对一团糟代码的你~~~真的想说,What F~U~C~K!!! 回归正题 ...

  8. 前后端数据交互(五)——什么是 axios?

    一.什么是 axios ? axios是基于 Promise 的 ajax 封装库,也是前端目前最流行的 ajax 请求库.简单地说发送 get.post 请求,是一个轻量级的库,使用时可直接引入. ...

  9. vue axios请求/响应拦截器

    // main.js中配置 // 引入 axios import Axios from 'axios' // 这时候如果在其它的组件中,是无法使用 axios 命令的. // 但如果将 axios 改 ...

随机推荐

  1. js缓慢运动,Math.ceil向上取整,floor向下取整

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  2. 杭电2019 数列有序!(STL解法)

    由于这题对于学过数据结构的我来说,真的是很简单,为了减少时间上的损失,链表无疑是最好的选择(因为数组要往后移位子).然后,因为最近想玩些STL的骚操作,所以就用<list>了,然后顺便学了 ...

  3. Codeforces Round #581 (Div. 2)D(思维,构造,最长非递减01串)

    #define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;char s[100007];int main ...

  4. Vue入口页

    Template里面的App就是在这个实例里面注册的App组件 也就是整个过程就是将el所标识的元素替换成<App/> 而App就是在此实例注册的App组件.

  5. kafka的搭建,命令

    a)kafka搭建 1.解压 2.修改配置/software/kafka_2.11-0.11.0.3/config/server.properties broker.id=0 log.dirs=/va ...

  6. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 按钮:制作一个大按钮

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  7. python学习第二课——while循环

    #while循环基础语句 while 1==1: print('OK') #死循环 #如何阻止死循环 count=0 while count<10: print('第'+(str)(count) ...

  8. 中国6G为什么要从现在上路?

    现在,通信5G的概念早已深入人心,正在从蓝图上的规划走向现实,平心而论,中国在2G/3G/4G时代都没有太突出的表现,或受制于人.或沦为跟随者,如今中国想翻身,于是从一开始就卯足了劲儿抢跑5G,不仅把 ...

  9. 三、java基础-方法含义_重载_递归

    1.java中方法: 方法的含义: 就是一个代码片段,可以完后某个特定的功能,可以重复利用: 定义方法的语法: [方法的修饰符列表]   方法的返回值类型   方法名{    java语句; } 注意 ...

  10. R语言 subset()函数用法

    subset() 函数: subset(dataset , subset , select ) dataset 是 要进行操作的数据集 subset 是对数据的某些字段进行操作 select 选取要显 ...