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 如何取消已发送的请求?
前言 最近在项目中遇到一个问题,在连续发送同一请求时,如果第二次请求比第一次请求快,那么实际显示的是第一次请求的数据,这就会造成数据和我选择的内容不一致的问题.解决的方案:在后续发送请求时,判断之前的 ...
随机推荐
- POJ3076 Sudoku
POJ3076 Sudoku 本题为16*16宫格 剪枝见代码 #include <cstdio> #include <iostream> #include <algor ...
- ES6(二) 函数
箭头函数 是简写,不要function 1.如果有且仅有一个参数,()可以不写 2.如果有且仅有一条语句,而且是return,{}也可以不写 let arr=[12,23,5,6] // arr.so ...
- 使用百度地图API查地理坐标
在网络编程中,我们会和API打交道.那么,什么是API?如何使用API呢?本文分享了一下我对API的理解以及百度地图API的使用. API是"Application Programming ...
- C# Directory和DirectoryInfo类(文件目录操作)
对目录操作例子: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...
- linux下获取系统时间 和 时间偏移
获取linux时间 并计算时间偏移 void getSystemTimer(void){#if 0 char *wdate[]={"Sun","Mon",&q ...
- elasticsearch-7.0.0-windows 安装
一.安装 1.下载压缩包 elasticsearch-7.0.0-windows-x86_64.zip 2.解压到 E:\env\elasticsearch-7.0.0 3.启动:进入 ...
- easygui.py的安装和下载地址
easygui下载地址:http://nchc.dl.sourceforge.net/project/easygui/0.97/easygui-0.97.zip 安装:解压后将easygui.py拷贝 ...
- Request.QueryString 的用法
比如常见的URL网页地址都有 xxx.asp?type=reLogin ?号后面的就是querystring querystring是asp中获取数据的一个方法. 那么就可以用request.qu ...
- Android学习系列--App列表之拖拽ListView(上)
研究了很久的拖拽ListView的实现,受益良多,特此与尔共飨. 鉴于这部分内容网上的资料少而简陋,而具体的实现过程或许对大家才有帮助,为了详尽而不失真,我们一步一步分析,分成两篇文章. 一 ...
- 4、在Shell程序中的使用变量
学习目标变量的赋值变量的访问变量的输入 12-4-1 变量的赋值在Shell编程中,所有的变量名都由字符串组成,并且不需要对变量进行声明.要赋值给一个变量,其格式如下:变量名=值.注意:等号(=)前后 ...