封裝mpvue請求文件
一陪毡、flyio是什么?
flyio.js 是一個基于 promise 的勾扭,輕量且強大的Javascript http 網(wǎng)絡庫
二毡琉、flyio的特點?
提供統(tǒng)一的 Promise API妙色。
瀏覽器環(huán)境下桅滋,輕量且非常輕量 。
支持多種JavaScript 運行環(huán)境
支持請求/響應攔截器。
自動轉換 JSON 數(shù)據(jù)丐谋。
支持切換底層 Http Engine芍碧,可輕松適配各種運行環(huán)境。
瀏覽器端支持全局Ajax攔截 号俐。
H5頁面內(nèi)嵌到原生 APP 中時泌豆,支持將 http 請求轉發(fā)到 Native。支持直接請求圖片吏饿。
安裝:
//安裝 fly
npm i flyio --save
配置公共配置:
src/http/config.JS
/*
fly 配置文件
by:David 2018.6.14
*/
// 引入 fly
var Fly = require("flyio/dist/NPM/wx")
var fly = new Fly;
import config from '@/config'
// 配置請求基地址
// // 定義公共 headers
// fly.config.headers={xx:5,bb:6,dd:7}
// // 設置超時
fly.config.timeout = 20000;
// // 設置請求基地址
fly.config.baseURL = config.host
// 添加請求攔截器
fly.interceptors.request.use((request) => {
// 給所有請求添加自定義 header
request.headers["X-Tag"] = "flyio";
// 打印出請求體
// console.log(request.body)
// 終止請求
//var err=new Error("xxx")
//err.request=request
//return Promise.reject(new Error(""))
// 可以顯式返回 request, 也可以不返回, 沒有返回值時攔截器中默認返回 request
return request;
})
// 添加響應攔截器, 響應攔截器會在 then/catch 處理之前執(zhí)行
fly.interceptors.response.use(
(response) => {
// 只將請求結果的 data 字段返回
return response.data
},
(err) => {
// 發(fā)生網(wǎng)絡錯誤后會走到這里
//return Promise.resolve("ssss")
}
)
// Vue.prototype.$http=fly // 將 fly 實例掛在 vue 原型上
export default fly
配置個性設置:
src/http/API.JS
import fly from './config'
import qs from 'qs'
import config from '../config'
const host = config.host;
const appKey = config.appKey;
const appid = config.appid;
/**
* 接口模版 ====post
*
* export const test = params => {return fly.post(`${root}/xx/xx`, qs.stringify(params))};
*
* 接口模版 ====get
*
* export const test1 = function(){return fly.get(`${root}/API/getNewsList`)}
*
*
* 用法:
* 在 頁面用引入 test
* import {test} from '../../http/API.JS'
*
* test(params).then(res=>{ console.log(res) })
*/
// 通用的 get 請求
export const get = (params) => {
return fly.get(`${host}${params.url}`, qs.stringify(params.data))
};
// 通用的 post 請求
export const post = (params) => {
return fly.post(`${host}${params.url}`, qs.stringify(params.data))
};
// 封裝的登錄請求, 根據(jù)后臺接收方式選擇是否加 qs.stringify
export const login = params => {
return fly.post('/login', params)
};
公共地址配置:
const host = 'http://xxx.xxx';
const appid = '';
const appKey = '';
const config = {
host,
appid,
appKey,
}
export default config
如果感覺有幫助留下一個寶貴的贊或者給小編一個贊賞W傥!!
同時如果想了解更多內(nèi)容可以關注下方公眾號: