接口封裝


在項目的開發過程中,我們也少不了與后台服務器進行數據的獲取和交互,這一般都是通過接口完成的,那么我們如何進行合理的接口配置呢?我們可以在 src 目錄下新建 services 文件夾用於存放接口文件:

└── src

    └── services

        ├── http.js      # 接口封裝

        ├── moduleA.js    # A模塊接口

        └── moduleB.js    # B模塊接口

為了讓接口便於管理,我們同樣使用不同的文件來配置不同模塊的接口,同時由於接口的調用 ajax 請求代碼重復部分較多,我們可以對其進行簡單的封裝,比如在 http.js 中(fetch為例):

/* http.js */import 'whatwg-fetch'

// HTTP 工具類export default class Http {

    static async request(method, url, data) {

        const param = {

            method: method,

            headers: {

                'Content-Type': 'application/json'

            }

        };

 

        if (method === 'GET') {

            url += this.formatQuery(data)

        } else {

            param['body'] = JSON.stringify(data)

        }

 

        // Tips.loading(); // 可調用 loading 組件

 

        return fetch(url, param).then(response => this.isSuccess(response))

                .then(response => {

                    return response.json()

            })

    }

 

    // 判斷請求是否成功

    static isSuccess(res) {

        if (res.status >= 200 && res.status < 300) {

            return res

        } else {

            this.requestException(res)

        }

    }

 

    // 處理異常

    static requestException(res) {

        const error = new Error(res.statusText)

 

        error.response = res

 

        throw error

    }

    

    // url處理

    static formatQuery(query) {

        let params = [];

 

        if (query) {

            for (let item in query) {

                let vals = query[item];

                if (vals !== undefined) {

                    params.push(item + '=' + query[item])

                }

            }

        }

        return params.length ? '?' + params.join('&') : '';

    }

    

    // 處理 get 請求

    static get(url, data) {

        return this.request('GET', url, data)

    }

    

    // 處理 put 請求

    static put(url, data) {

        return this.request('PUT', url, data)

    }

    

    // 處理 post 請求

    static post(url, data) {

        return this.request('POST', url, data)

    }

    

    // 處理 patch 請求

    static patch(url, data) {

        return this.request('PATCH', url, data)

    }

    

    // 處理 delete 請求

    static delete(url, data) {

        return this.request('DELETE', url, data)

    }

}

封裝完畢后我們在 moduleA.js 中配置一個 github 的開放接口:https://api.github.com/repos/octokit/octokit.rb

/* moduleA.js */import Http from './http'

// 獲取測試數據export const getTestData = () => {

    return Http.get('https://api.github.com/repos/octokit/octokit.rb')

}

然后在項目頁面中進行調用,會成功獲取 github 返回的數據,但是一般我們在項目中配置接口的時候會直接省略項目 url 部分,比如:

/* moduleA.js */import Http from './http'

// 獲取測試數據export const getTestData = () => {

    return Http.get('/repos/octokit/octokit.rb')

}

這時候我們再次調用接口的時候會發現其調用地址為本地地址:http://127.0.0.1:8080/repos/octokit/octokit.rb,那么為了讓其指向 https://api.github.com,我們需要在 vue.config.js 中進行 devServer 的配置:

/* vue.config.js */

module.exports = {

    ...

    

    devServer: {

    

        // string | Object 代理設置

        proxy: {

        

            // 接口是 '/repos' 開頭的才用代理

            '/repos': {

                target: 'https://api.github.com', // 目標地址

                changeOrigin: true, // 是否改變源地址

                // pathRewrite: {'^/api': ''}

            }

        },

    }

    

    ...

}

devServer 中 我們配置 proxy 進行接口的代理,將我們本地地址轉換為真實的服務器地址,此時我們同樣能順利的獲取到數據,不同點在於接口狀態變成了 304(重定向):

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM