在uni-app中使用axios
安装axios
首先在项目文件夹打开终端
运行npm install axios
安装完成后在node_modules
文件夹下会有名为axios
和follow-redirects
的目录
配置axios
封装axios
创建utils/request/request.js
import Vue from 'vue'
import axios from 'axios'
// create an axios instance
const service = axios.create({
baseURL: 'http://localhost:9898', // url = base url + request url
//withCredentials: true, // send cookies when cross-domain requests 注意:withCredentials和后端配置的cross跨域不可同时使用
timeout: 1000, // request timeout
crossDomain: true
})
// 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 => {
if (error.response.status) {
switch (error.response.status) {
case 401:
break;
default:
break;
}
}
return Promise.reject(error)
})
// 在main.js中放入这段自定义适配器的代码,就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求,并支持携带cookie
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) {
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
- 注意配置其中的
baseURL
- 其中有些参数要根据实际项目参数名设置
- 含跨域网络请求问题解决方案
- withCredentials允许获取cookie 和后端配置的跨域不可同时使用,会报错
配置全局axios
在项目根目录的main.js
中头部配置如下:
// 引入封装后的axios
import axios from './utils/request/request.js'
/**
* 给Vue函数添加一个原型属性$axios 指向Axios
* 这样做的好处是在vue实例或组件中不用再去重复引用Axios 直接用this.$axios就能执行axios 方法了
* 在.vue中使用,this.$axios.get
* @param {Object} config
*/
Vue.prototype.$axios = axios
使用axios
在配置了全局的axios后就可以在项目的任意位置使用axios
login() {
var that = this;
if (!that.username) {
uni.showToast({
title: '请输入您的用户名',
icon: 'none'
});
return;
}
// if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(that.username)) {
// uni.showToast({ title: '请输入正确手机号', icon: 'none' });
// return;
// }
if (!that.password) {
uni.showToast({
title: '请输入您的密码',
icon: 'none'
});
return;
}
this.$axios({
method:'POST',
url:'/crm/user/login',
params:{
'userName':that.username,
'userPwd':that.password
}
}).then(res=>{
//登录成功
uni.setStorageSync('trueName', res.result.trueName);
uni.setStorageSync('userIdStr', res.result.userIdStr);
uni.setStorageSync('userName', res.result.userName);
//关闭当前页面并转到主页面
uni.redirectTo({
url: '../index/index'
});
console.log(res.result)
}).catch(err=>{
console.log(err);
if(err.msg == '用户密码不正确'){
uni.showToast({
title: '用户密码不正确',
icon: 'none'
});
}else if(err.msg == '用户名不存在'){
uni.showToast({
title: '用户名不存在',
icon: 'none'
});
}else{
uni.showToast({
title: '系统异常,请重试',
icon: 'none'
});
}
})
}
参考:https://blog.csdn.net/mrs_chens/article/details/108417977
赞赏
- 本文作者: 况杨
- 本文链接: https://kuangyang828.github.io/zai-uni-app-zhong-shi-yong-axios/
- 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
0%
x
感谢您的支持,我会继续努力的!


扫码打赏,你说多少就多少
打开微信扫一扫,即可进行扫码打赏哦
支付宝
微信支付