在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的方法分享。

 

/****************************我是可愛的分割線********************************/


免責聲明!

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



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