axios在uniapp中的使用

稻草人_9ac7
2020.07.24 20:30:29

// service.js文件

import Vue from 'vue'
import axios from 'axios'
let baseURL = 'http://192.168.0.184:4001/user/'
const service = axios.create({
    withCredentials: true,
    crossDomain: true,
    baseURL,
    timeout: 6000
})

// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
    config => {
        // if (store.state.token) {
        //     // 给请求头添加user-token
        //     config.headers["user-token"] = store.state.token;
        // }
        console.log('请求拦截成功')
        return config;
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

//配置成功后的拦截器
service.interceptors.response.use(res => {
    if (res.data.status== 200) {
        return res.data
    } else {
        return Promise.reject(res.data.msg);
    }
}, error => {
    return Promise.reject(error)
})


axios.defaults.adapter = function(config) { //自己定义个适配器,用来适配uniapp的语法
    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) {
                console.log("执行完成:",response)
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}
export default service

// main.js文件

import Vue from 'vue';
import App from './App';
import axios from './api/request.js'

Vue.config.productionTip = false;
Vue.prototype.$axios = axios

// user.js文件

const api = require("./api.js");
import Vue from 'vue';

// 获取登陆验证码
export const userRegister = (params) => {
    console.log("请求Vue:",Vue)
    return Vue.prototype.$axios.post(
        api.REGISTERVERIFICATIONCODE,
        params
    )
}
// index.vue 组件文件中
const USERS = require("../../api/users")
//.........
USERS.userRegister(params).then(res => {
            console.log("获取登陆验证码成功啦:",res)
        }).catch(err => {
            console.log("获取验证码失败啦:",err)
        })

参考资料:
axios在vue中的封装
axios请求数据获取成功了,但没有走then而是走了catch

Logo

前往低代码交流专区

更多推荐