Axios介绍和使用
一、介绍
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。 官方资料和介绍
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
二、Axios的基本使用
1、Axios安装方法
使用npm:
$ npm install axios
使用bower:
$ bower install axios
使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2、axios项目配置准备
$ npm init --yes
{
"name": "code",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
$ npm install vue -S;npm install axios -S
code@1.0.0 /Users/hqs/PycharmProjects/vue_study/04-axios的基本使用/code
└── vue@2.6.10
code@1.0.0 /Users/hqs/PycharmProjects/vue_study/04-axios的基本使用/code
└─┬ axios@0.18.0
├─┬ follow-redirects@1.7.0
│ └─┬ debug@3.2.6
│ └── ms@2.1.1
└── is-buffer@1.1.6
3、服务端配置准备
# 1.pip3 install Flask
# 2.python3 server.py
import json
from flask import Flask
from flask import request
from flask import Response
app = Flask(__name__)
# 默认是get请求
@app.route("/")
def index():
resp = Response("<h2>首页</h2>")
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
@app.route("/course")
def courses():
resp = Response(json.dumps({
"name": "alex"
}))
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
@app.route("/create", methods=["post",])
def create():
print(request.form.get('name'))
with open("user.json", "r") as f:
# 将数据反序列化
data = json.loads(f.read())
data.append({"name": request.form.get('name')})
with open("user.json", "w") as f:
f.write(json.dumps(data))
resp = Response(json.dumps(data))
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
if __name__ == '__main__':
app.run(host="localhost", port=8800)
服务端代码如上所示,再编辑user.json文件如下:
[{"name": "alex"}]
4、axios发送请求
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>
<script type="text/javascript">
var App = {
data(){
return {
msg: ''
}
},
template:`
<div>
<button @click='sendAjax'>发Get请求</button>
<div v-html="msg"></div>
<button @click="sendAjaxByPost">发post请求</button>
</div>
`,
methods:{
sendAjax(){
// 发送get请求
axios.get("http://127.0.0.1:8800/"
).then(res=>{
console.log(res.data); // <h2>首页</h2>
console.log(typeof res.data); // string
this.msg = res.data;
}).catch(err=>{ // 有参数括号可以不写
console.log(err);
})
},
sendAjaxByPost(){
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
axios.post('http://127.0.0.1:8800/create', params
).then(function (res) {
console.log(res);
}).catch(err=>{
console.log(err);
})
}
}
};
new Vue({
el: "#app",
data(){
return {
}
},
components:{
App
},
template: `<App/>`
})
</script>
</body>
(1) 发起一个GET请求
methods:{
sendAjax(){
// 发送get请求
axios.get("http://127.0.0.1:8800/"
).then(res=>{
console.log(res.data); // <h2>首页</h2>
console.log(typeof res.data); // string
this.msg = res.data;
}).catch(err=>{ // 有参数括号可以不写
console.log(err);
})
}
}
点击发送get请求的按钮,console输出的实例化对象如下所示:
(2)发起一个POST请求
methods:{
sendAjaxByPost(){
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
axios.post('http://127.0.0.1:8800/create', params
).then(function (res) {
console.log(res);
}).catch(err=>{
console.log(err);
})
}
}
点击发送post请求,console输出的实例化对象如下所示:
user.json文件内容变化为如下内容:
[{"name": "alex"}, {"name": "hqs"}]
5、axios的默认配置
vue和axios都是全局对象,未来axios会成为局部作用域.可以给Vue的原型挂载一个属性$axios:
Vue.prototype.$axios = axios;
此时我们就可以在任意组件中通过this.$axios获取到当前的axios实例。
<!--vue和axios都是全局对象,未来axios会成为局部作用域-->
<script type="text/javascript">
// 挂载,给Vue的原型挂载一个属性$axios,使用插件
Vue.prototype.$axios = axios;
// 配置公共的url
axios.defaults.baseURL = 'http://127.0.0.1:8800';
var App = {
data(){
return {
msg: ''
}
},
template:`
<div>
<button @click='sendAjax'>发Get请求</button>
<div v-html="msg"></div>
<button @click="sendAjaxByPost">发post请求</button>
</div>
`,
methods:{
sendAjax(){
// 发送get请求,直接拼接公共Url
this.$axios.get("/"
).then(res=>{
console.log(res.data); // <h2>首页</h2>
console.log(typeof res.data); // string
this.msg = res.data;
}).catch(err=>{ // 有参数括号可以不写
console.log(err);
})
},
sendAjaxByPost(){
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
this.$axios.post('/create', params
).then(function (res) {
console.log(res);
}).catch(err=>{
console.log(err);
})
}
}
};
// 代码省略
</script>
6、使用axios的this指向问题
在前端框架中一定要使用箭头函数,不建议使用es5中的普通函数,因为它会使this的指向发生改变。
(1)this指向问题现象
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>
<!--vue和axios都是全局对象,未来axios会成为局部作用域-->
<script type="text/javascript">
// 挂载,给Vue的原型挂载一个属性$axios,使用插件
Vue.prototype.$axios = axios;
// 配置公共的url
axios.defaults.baseURL = 'http://127.0.0.1:8800';
var App = {
data(){
return {
msg: '',
datas: []
}
},
template:`
<div>
<button @click='sendAjax'>发Get请求</button>
<div v-html="msg"></div>
<button @click="sendAjaxByPost">发post请求</button>
{{datas}}
</div>
`,
methods:{
sendAjax(){
// 发送get请求,直接拼接公共Url
this.$axios.get("/"
).then(res=>{
console.log(res.data); // <h2>首页</h2>
console.log(typeof res.data); // string
this.msg = res.data;
}).catch(err=>{ // 有参数括号可以不写
console.log(err);
})
},
sendAjaxByPost(){
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
this.$axios.post('/create', params
).then(function (res) {
console.log(res);
console.log(this); // 输出window示例对象(自动转化为windows对象)
// 初学者易犯的错
this.datas = res;
}).catch(err=>{
console.log(err);
})
}
}
};
new Vue({
el: "#app",
data(){
return {
}
},
components:{
App
},
template: `<App/>`
})
</script>
</body>
回调函数中的this从axios改为了windows,console输出如下所示:
(2)使用箭头函数解决this指向问题
在vue中使用函数时,推荐使用箭头函数可以解决this的指向问题。
sendAjaxByPost(){
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
this.$axios.post('/create', params
).then((res)=> {
console.log(res);
console.log(this);
// 初学者易犯的错
this.datas = res;
}).catch(err=>{
console.log(err);
})
}
点击发送post请求按钮,显示效果如下所示:
(3)使用局部变量解决this指向问题(不推荐)
sendAjaxByPost(){
var _this = this;
var params = new URLSearchParams();
params.append('name', 'hqs');
// 发送post请求
this.$axios.post('/create', params
).then(function (res) {
console.log(res);
console.log(this);
// 初学者易犯的错
this.datas = res;
}).catch(err=>{
console.log(err);
})
}
Axios介绍和使用的更多相关文章
- Vuex与axios介绍
Vuex集中式状态管理里架构 axios (Ajax) Vuex集中式状态管理架构 -简单介绍: vuex是一个专门为Vue.js设计的集中式状态管理架构. 我们把它理解为在data中需要共享给其他组 ...
- axios介绍与使用说明 axios中文文档
本周在做一个使用vuejs的前端项目,访问后端服务使用axios库,这里对照官方文档,简单记录下,也方便大家参考. Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node ...
- axios介绍
原文地址:lewis1990@amoy axios 基于promise用于浏览器和node.js的http客户端 特点 支持浏览器和node.js 支持promise 能拦截请求和响应 能转换请求和响 ...
- vue项目中关于axios的简单使用
axios介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中 官方仓库:https://github.com/axios/axios 中文文档:htt ...
- Axios 是一个基于 promise 的 HTTP 库
Axios 是一个基于 promise 的 HTTP 库 vue项目中关于axios的简单使用 axios介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.j ...
- (生产)axios - 请求接口
参考:https://www.awesomes.cn/repo/mzabriskie/axios axios 介绍 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中 ...
- promise和axios
1.接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环境是「单线程」 所谓单线程,是指JS引擎中负责解释和执行JavaScript代码的 ...
- Reactjs之Axios、fetch-jsonp获取后台数据
1.新增知识点 /** Axios获取服务器数据(无法跨域,只能让后台跨域获取数据) react获取服务器APi接口的数据: react中没有提供专门的请求数据的模块.但是我们可以使用任何第三方请求数 ...
- axios 如何取消已发送的请求?
前言 最近在项目中遇到一个问题,在连续发送同一请求时,如果第二次请求比第一次请求快,那么实际显示的是第一次请求的数据,这就会造成数据和我选择的内容不一致的问题.解决的方案:在后续发送请求时,判断之前的 ...
随机推荐
- Python2和Python3之间的区别
编码区别 Python3.X版本中源码文件默认使用的是utf-8编码 Unicode 字符串 Python 2有两种字符串类型:Unicode字符串和非Unicode字符串 Python 3只有一种类 ...
- 条目二十八《正确理解由reverse_iterator的base()成员函数所产生的iterator的用法》
条目二十八<正确理解由reverse_iterator的base()成员函数所产生的iterator的用法> 迭代器的种类一共有四种,上面已经说过了.这里就不再次写出来. 这一个条目主要是 ...
- 提交app时候遇到IDFA警告
1.最近提交app时候遇到如下问题,解决方案: Everything has come to its usual state now. Simply upload your binary as you ...
- Codeforces Round #556 题解
Codeforces Round #556 题解 Div.2 A Stock Arbitraging 傻逼题 Div.2 B Tiling Challenge 傻逼题 Div.1 A Prefix S ...
- truffle使用详解
truffle使用详解 truffle是什么 Truffle测试环境 安装truffle truffle项目结构解析 文件编译 truffle的配置文件 移植 与合约进行交互 1.truffle是什么 ...
- Angular material mat-icon 资源参考_File
ul,li>ol { margin-bottom: 0 } dt { font-weight: 700 } dd { margin: 0 1.5em 1.5em } img { height: ...
- Oracle DMP
通过DMP对Oracle数据库进行导入导出 打开“开始”--->输入cmd,打开cmd命令窗口,输入以下命令即可 1导出 (1)将数据库ORACLE完全导出,用户名system密码manager ...
- Python 实现flatten功能
from collections import Iterable def flatten(items): for x in items: if isinstance(x, Iterable) and ...
- js中的new操作符与Object.create()的作用与区别
js中的new操作符与Object.create()的作用与区别 https://blog.csdn.net/mht1829/article/details/76785231 2017年08月06日 ...
- unittest简介
unittest是python里面的单元测试框架 1 unittest 简介 1).先导入 unittest2).用 help 函数查看源码解析3).查看描述:Python unit testing ...