美文网首页uniapp
【uniapp】vue-cli微信小程序使用flyio

【uniapp】vue-cli微信小程序使用flyio

作者: somliy | 来源:发表于2020-03-06 10:08 被阅读0次

为什么使用fly.js
微信小程序采用web开发技术栈,使用JavaScript语言开发,但是JavaScript运行时和浏览器又有所不同,导致axios、jQuery等库无法在微信小程序中使用,而flyio可以。

fly.js简介

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

在微信小程序中的使用

1. 引入fly.js,并添加到程序中

import Fly from 'flyio/dist/npm/wx'

const fly = new Fly();

// 基础请求
fly.config.baseURL = 'http://localhost:8888';

fly.config.timeout = 5000;

// 请求拦截器
fly.interceptors.request.use((request) => {
  return request
});

// 响应拦截器
fly.interceptors.response.use((response) => {
    return response.data
  }, (err, promise) => {
  return promise.reject(err.response.data)
});

export default fly;

2. 在main.js中声明

// 填写上述js文件路径
import fly from '....'

Vue.prototype.$request = fly;

如何使用

请求参考如下,只需在页面引用即可

import fly from '....'

// get 请求
export function getInfo () {
  return fly.request({
    url: '/sys/user/info',
    method: 'get'
  })
}

// post 请求
export function registerUser (data) {
  return fly.request({
    url: '/sys/user/registerUser',
    method: 'POST',
    body: data
  })
}

// 自定义请求头
export function login (params) {
  return fly.request({
    url: '/oauth/token',
    method: 'POST',
    body: params,
    headers: {
      'Authorization': 'Basic ....',
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

相关文章

网友评论

    本文标题:【uniapp】vue-cli微信小程序使用flyio

    本文链接:https://www.haomeiwen.com/subject/pbcvrhtx.html