一、介紹
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);
})
}