在uniapp设计的APP中引入axios,支持cookie(真机亲测可行)

  在uniapp中,我们可以通过原生的uni.request(OBJECT)方法发起网络请求,但是这个请求方式不管是在h5、app、还是微信小程序,都是不支持cookie的。这里就想到在vue项目中经常用到的请求方式axios,是支持cookie的,那我们是不是可以把axios也引入到uniapp中使用呢?有了这个想法,我们就开始动手做起来吧!

首先就是正常的安装和引用axios:

一.安装npm插件

在HbuilderX顶部菜单,选择工具—>插件安装,选择NPM安装。

 

二.安装axios

在你的uniapp项目的根目录下,运行命令行语句:

npm install axios

 

 

 

 执行完后会发现uniapp和vue的项目一样,多了一个node_module文件夹,文件夹中多了一个axios文件夹,即安装成功。

三.在main.js中引入axios

import Vue from 'vue'
import App from './App'
import axios from 'axios' // create an axios instance const service = axios.create({ baseURL: 'http://192.168.0.105:8090', // url = base url + request url withCredentials: true, // send cookies when cross-domain requests // timeout: 5000, // request timeout crossDomain: true }) Vue.prototype.$axios = service

四.创建axios.js文件,导出axios方法

import Vue from 'vue'

export default Vue.prototype.$axios

 

五.使用axios进行方法请求

到这一步,我们就可以用axios进行请求了。但是问题也来了,这个请求方式在h5中可以执行,但是在app和微信小程序运行的就会出现下面这个错误:

 

 

 adapter是axios的适配器,可在adapter中设置属于自己的请求方法,这里报错大概是axios默认的适配器并没有被uniapp识别到,所以我们在这里就自己定义个适配器。这里就是基于Promise封装了uniapp的request方法,代码如下:

axios.defaults.adapter = function(config) {
    return new Promise((resolve, reject) => {
        console.log(config)
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}

在main.js中放入这段自定义适配器的代码,就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求,并支持携带cookie。

 

以上就是uniapp引入axios的方法分享。

 

/****************************我是可爱的分割线********************************/

posted @ 2020-03-05 09:25  Merryan  阅读(19535)  评论(1编辑  收藏  举报