• 支持Vue家族全系框架的跨平台http请求库fly.js


    解决环境导致后端接口变换问题

    搞清楚这个问题后,我们就可以在不同环境的机器上设置不同的 NODE_ENV,当然这个字段也不一定。
    你也可以换成其他的NODE_ENV_NIZUISHUAI等等,反正是自定义的。

    解决步骤

    1.修改代码里的后端地址配置

    很简单,就是利用 process.env.NODE_ENV这个字段来判断。(processnode全局属性,直接用就行了)

     clipboard.png

    request.js

    import Fly from 'flyio/dist/npm/fly';
    const fly = new Fly();

    const APP_API = process.env.NODE_ENV === 'development' ? '/api' : 'https://api.scms.sztv.com.cn' ;

    // 设置请求基地址
    fly.config.baseURL = `${APP_API}`;

    // 添加请求拦截器
    fly.interceptors.request.use((request) => {
    request.timeout = 30000;
    request.headers = {
    "content-type": "application/json",
    "authorization": ""
    }
    return request;
    })

    // 添加响应拦截器,响应拦截器会在then/catch处理之前执行
    fly.interceptors.response.use(
    (response) => {
    let responseData = response.data;
    //拦截需要登录的接口,当未登录的时候,弹出登录框
    if(responseData.code == -41003){
    }
    // 只将请求结果的data字段返回
    return Promise.resolve(responseData)
    },
    (err) => {
    return Promise.reject(err);
    }
    )
    export { fly }


    api.js

    import {fly} from './request'


    export const API = {
    /*增加评论接口*/
    addComment: (paramObj) => fly.get('api/com/comment/add', paramObj),
    /*获取评论接口*/
    getComment: (paramObj) => fly.get('api/com/comment/list',paramObj),
    getShare:(paramObj) => fly.get('api/weixin/jstoken',paramObj),
    }
     

     vue.config.js

    module.exports = {
    publicPath:'./',
    productionSourceMap:false,
    chainWebpack: config => {
    config
    .plugin('html')
    .tap(args => {
    args[0].title= '学习贯彻党的十九届六中全会精神-各区书记系列访谈'
    return args;
    })
    },
    devServer: {
    proxy: {
    '/api': {
    target: 'https://api.scms.sztv.com.cn',
    changOrigin: true, //允许跨域
    pathRewrite: {
    '^/api': ''
    }
    },
    }
    }
    }

     

     

    官方文档:https://wendux.github.io/dist/#/doc/flyio/readme

    https://wendux.github.io/dist/#/doc/flyio/readme

    Github: https://github.com/wendux/fly           

    Fly.js 一个基于Promise的、强大的、支持多种JavaScript运行时的http请求库. 有了它,您可以使用一份http请求代码在浏览器、微信小程序、Weex、Node中都能正常运行。同时可以方便配合 Vue家族的框架,最大可能的实现 Write Once, Run Everywhere。

    问题
    随着 Weex 、mpvue 的发布,他们都是支持Vue.js语法。目前vue已经你能够运行在浏览器、小程序和Native了。尽管各个平台仍有差异,但已经基本能实现 Write Once Run Everywhere 。这使得我们可以在多个端上实现尽可能大限度在代码复用。但是无论是 vue 还是Weex 、mpvue,它们本质上都只是一个View层,也就说最好的情况,也只能实现UI复用。但对于一个应用程序来说,除了UI,最重要的就是数据了,而数据来源一般都是来自网络请求(大多数都是http)。在使用这些框架时,您的网络请求,都需要使用平台特定的API!这很糟糕,意味着您网络请求的代码不能复用,所以尽管UI可以复用,但我们还需要去适配网络请求部分的代码。

    一致的网络请求
    要解决这个问题,就需要一个能支持多个平台网络库,用户层提供统一的API,将平台差异在底层屏蔽。而 Fly.js就是这酱紫的一个网络库,为了方便axios使用者迁移,fly.js API设计风格和axios相似(但不完全相同)!

    Fly.js 通过在不同 JavaScript 运行时通过在底层切换不同的 Http Engine来实现多环境支持,但同时对用户层提供统一、标准的Promise API。不仅如此,Fly.js还支持请求/响应拦截器、自动转化JSON、请求转发等功能,详情请参考:https://github.com/wendux/fly

    已支持的平台
    目前Fly.js支持的平台包括:Node.js 、微信小程序 、Weex 和浏览器,这些平台的 JavaScript 运行时都是不同的。更多的平台正在持续添加中,请保持关注。

    Fly简单使用示例
    下面示例如无特殊说明,则在所有支持的平台下都能执行。

    发起GET请求
    //不同平台可能需要引入不同文件,详情见文档
    var fly=require("flyio")

    //通过用户id获取信息,参数直接写在url中
    fly.get('/user?id=133')
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
    console.log(error);
    });

    //query参数通过对象传递
    fly.get('/user', {
    id: 133
    })
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
    console.log(error);
    });

    发起POST请求
    fly.post('/user', {
    name: 'Doris',
    age: 24
    phone:"18513222525"
    })
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
    console.log(error);
    });

    发起多个并发请求
    function getUserRecords() {
    return fly.get('/user/133/records');
    }

    function getUserProjects() {
    return fly.get('/user/133/projects');
    }

    fly.all([getUserRecords(), getUserProjects()])
    .then(fly.spread(function (records, projects) {
    //两个请求都完成
    }))
    .catch(function(error){
    console.log(error)
    })

    拦截器
    Fly支持请求/响应拦截器,可以通过它在请求发起之前和收到响应数据之后做一些预处理。


    //添加请求拦截器
    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处理之前执行
    fly.interceptors.response.use(
    (response) => {
    //只将请求结果的data字段返回
    return response.data
    },
    (err) => {
    //发生网络错误后会走到这里
    //return Promise.resolve("ssss")
    }
    )

    除过以上这些使用,Fly.js 还有很多其它强大的功能,详情请移步Fly.js.

    反馈
    如果您有问题欢迎在 在github 提issue . fly.js github: https://github.com/wendux/fly
    ————————————————
    版权声明:本文为CSDN博主「lazy杜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/duwen90/article/details/79624029

  • 相关阅读:
    (转)PHP获取今天、昨天、明天的日期
    (转)META http-equiv="refresh" 实现网页自动跳转
    (转)PHP中文处理 中文字符串截取(mb_substr)和获取中文字符串字数
    (转)Apache2 httpd.conf 配置详解 (二)
    Process finished with exit code 129
    Importing image to python :cannot import name 'imread'
    CUDA运行时错误 --- CUDA_ERROR_LAUNCH_FAILED: unspecified launch failure
    Recommendation system
    php手动实现ip2long和long2ip
    git将某个分支的代码完全覆盖另一个分支
  • 原文地址:https://www.cnblogs.com/2019gdiceboy/p/15686318.html
Copyright © 2020-2023  润新知