Axios介紹和使用

1、介紹

Axios 是一個基於 promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中。 官方資料和介紹javascript

  • 從瀏覽器中建立 XMLHttpRequests
  • 從 node.js 建立 http 請求
  • 支持 Promise API
  • 攔截請求和響應
  • 轉換請求數據和響應數據
  • 取消請求
  • 自動轉換 JSON 數據
  • 客戶端支持防護 XSRF

2、Axios的基本使用

一、Axios安裝方法

使用npm:html

$ npm install axios

使用bower:前端

$ bower install axios

使用cdn:vue

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、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

三、服務端配置準備

# 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文件以下:java

[{"name": "alex"}]

四、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輸出的實例化對象以下所示:node

get請求

(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輸出的實例化對象以下所示:
post請求python

user.json文件內容變化爲以下內容:
[{"name": "alex"}, {"name": "hqs"}]ios

五、axios的默認配置

vue和axios都是全局對象,將來axios會成爲局部做用域.能夠給Vue的原型掛載一個屬性$axios:npm

Vue.prototype.$axios = axios;json

此時咱們就能夠在任意組件中經過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>

六、使用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輸出以下所示:
this對象

(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);
    })
}
相關文章
相關標籤/搜索