一、介绍

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介绍和使用的更多相关文章

  1. Vuex与axios介绍

    Vuex集中式状态管理里架构 axios (Ajax) Vuex集中式状态管理架构 -简单介绍: vuex是一个专门为Vue.js设计的集中式状态管理架构. 我们把它理解为在data中需要共享给其他组 ...

  2. axios介绍与使用说明 axios中文文档

    本周在做一个使用vuejs的前端项目,访问后端服务使用axios库,这里对照官方文档,简单记录下,也方便大家参考. Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node ...

  3. axios介绍

    原文地址:lewis1990@amoy axios 基于promise用于浏览器和node.js的http客户端 特点 支持浏览器和node.js 支持promise 能拦截请求和响应 能转换请求和响 ...

  4. vue项目中关于axios的简单使用

    axios介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中 官方仓库:https://github.com/axios/axios 中文文档:htt ...

  5. Axios 是一个基于 promise 的 HTTP 库

    Axios 是一个基于 promise 的 HTTP 库 vue项目中关于axios的简单使用 axios介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.j ...

  6. (生产)axios - 请求接口

    参考:https://www.awesomes.cn/repo/mzabriskie/axios axios 介绍 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中 ...

  7. promise和axios

    1.接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环境是「单线程」 所谓单线程,是指JS引擎中负责解释和执行JavaScript代码的 ...

  8. Reactjs之Axios、fetch-jsonp获取后台数据

    1.新增知识点 /** Axios获取服务器数据(无法跨域,只能让后台跨域获取数据) react获取服务器APi接口的数据: react中没有提供专门的请求数据的模块.但是我们可以使用任何第三方请求数 ...

  9. axios 如何取消已发送的请求?

    前言 最近在项目中遇到一个问题,在连续发送同一请求时,如果第二次请求比第一次请求快,那么实际显示的是第一次请求的数据,这就会造成数据和我选择的内容不一致的问题.解决的方案:在后续发送请求时,判断之前的 ...

随机推荐

  1. (转载)一位资深程序员大牛给予Java初学者的学习建议

    这一部分其实也算是今天的重点,这一部分用来回答很多群里的朋友所问过的问题,那就是我你是如何学习Java的,能不能给点建议? 今天我是打算来点干货,因此咱们就不说一些学习方法和技巧了,直接来谈每个阶段要 ...

  2. selenium+python+unittest:一个类中只执行一次setUpClass和tearDownClass里面的内容(可解决重复打开浏览器和关闭浏览器,或重复登录等问题)

    unittest框架是python自带的,所以直接import unittest即可,定义测试类时,父类是unittest.TestCase. 可实现执行测试前置条件.测试后置条件,对比预期结果和实际 ...

  3. Vue-cli3 WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB)

    在vue.config.js里 添加 configureWebpack : { performance: { hints:'warning', //入口起点的最大体积 整数类型(以字节为单位) max ...

  4. Gson使用

    Gson提供了fromJson()方法来实现从Json相关对象到Java实体的方法. 在日常应用中,我们一般都会碰到两种情况,转成单一实体对象和转换成对象列表或者其他结构. 先来看第一种: 比如jso ...

  5. 在浏览器中输入URL后,执行的全部过程。(一次完整的http请求过程)

    整个流程如下: 域名解析 为了将消息从你的PC上传到服务器 上.需要用到1P协议.ARP协议和0SPF协议 发起TCP的3次握手 建立TCP连接后发起http请求 服务器响应htp请求 浏览器解析ht ...

  6. 2019.03.29 读书笔记 关于override与new

    差异:override:覆盖父类分方法,new 隐藏父类方法. 共同:都不能改变父类自身方法. public class Test { public string Name { get; set; } ...

  7. 如何在react&webpack中引入图片?

    在react&webpack项目中需要引入图片,但是webpack使用的模块化的思想,如果不进行任何配置,而直接在jsx或者是css中使用相对路径来使用就会出现问题,在webpack中提供了u ...

  8. 使用not in的子查询

    operand comparison_operator [NOT] in (subquery) =ANY运算符与IN等效 !=ALL或<>ALL运算符与NOT IN 等效 如果子查询返回任 ...

  9. ORACLE迁移GP实践

    最近在做oracle到greenplum的迁移实践,步骤如下: 1. 使用ora2pg实现Oracle的数据结构迁移到GP的实现过程 2. Oracle的数据迁移到GP的实现过程   1. ora2p ...

  10. Git学习系列之一些常用的Git命令收录更新ing

    不多说,直接上干货!  前言 对于Git工具,有必要整理和总结一些常用实用的命令. http://p.primeton.com/articles/53cce3a3e138236138000026 ht ...