有问题就试试npm install axios
1.在根目录下创建 utils/request.js (在自己项目的请求js中配置)
import Vue from 'vue'
import axios from 'axios'
// 创建axios对象
const service = axios.create({
// 请求全路径url = base url + request url,其中request url就是发送请求时作为axios参数的路径
baseURL: 'http://192.168.1.8:8010/',
// 跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),也可以简单的理解为,当前请求为跨域类型时是否在请求中协带cookie。
// 注意:withCredentials和后端配置的cross跨域不可同时使用
// withCredentials: true,
// // // 请求超时时间
timeout: 5000,
// 是否跨域请求A
crossDomain: true
})
//request拦截器,在请求之前做一些处理
service.interceptors.request.use(config => {
//加上 config.headers 那么每次默认请求都会带上这个header 后端可以request.getheader去处理
config.headers["accessToken"] = uni.getStorageSync('accessToken');//每次请求都从缓存中读取 这一步一般都会登录成功后把第一个token存入到缓存当中
//我这里不加这个报错 之前没遇到过 默认其实是有这个的
config.headers["Content-Type"] = 'text/plain';
console.log('即将发送的请求的配置:', config);
return config;
});
//配置成功后的拦截器
service.interceptors.response.use(res => {
return res
}, error => {
if (error.response.status) {
switch (error.response.status) {
case 401:
break;
default:
break;
}
}
return Promise.reject(error)
})
// 在main.js中放入这段自定义适配器的代码,就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求
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);
}
})
})
}
export default service
2.在main.js中 添加import axios from './utils/request.js' , (全局引用request.js)
Vue.prototype.$axios = axios; (引入 this.$axios)
3.登录页面的方法 我的参数名称 user.username 后台是strtus2 上线前会换成json并加密 正常的话直接写 username就行
login() {
uni.showLoading({
title: '正在登录...'
});
debugger;
uni.hideLoading();
this.$axios({
method: 'POST',
url: '/mobile/loginAction!login.do?',
params: {
'user.userName': ,
'user.password': this.pwd,
},
}).then(res => {
debugger
var timestamp = Date.parse(new Date()) + 3600000;//设置token过期时间为1小时
// 存储密钥到缓存中
if (res.data.status == '200') {
console.log(res.data)//↓登录成功后往缓存中存放你的后台返回信息
uni.clearStorage();//每次重新登录我都清除缓存了 这一步是清除所有缓存
uni.setStorageSync('orgId', res.data.result.orgId);//业务ID
uni.setStorageSync('accessToken', res.data.token);//后台返回的token
uni.setStorageSync('timestampbeOverdue', timestamp);//token超时时间
uni.switchTab({
url: '/pages/zpdemo/page'
});
}
if (res.data.status == '401') {
uni.showModal({
title: '登录失败',
content: '用户名或密码错误',
success: (res) => {
if (res.confirm) {
this.oldKeywordList = [];
uni.removeStorage({
key: 'OldKeys'
});
} else if (res.cancenl) {
console.log("用户点击取消")
}
}
});
} else {
this.showTextmsg = true;
}
}).catch(res => {
debugger;
console.log('系统异常 请联系管理员');
console.log(res)
this.showTextmsg = true;
})
}
4. 封装js请求方式和传参格式 @RequestBody @RequestParame @PathVaild 我这里strtus2 没啥聊的
//引入request.js包
import request from '@/utils/request.js'
//↓data=json参数 params=路径传参 fromdata格式则需要增加header 而不需要改data、params
export const getlist = (data) => request({
url: '/mobile/cjHzpAction!hzpList.do',
method: 'POST',
data: data
});
//查询接口
export const queryCjHzInfo = (data) => request({
url: '/mobile/cjHzpAction!show.do',
method: 'POST',
data: data
});
//编辑提交接口
export const editCjHzInfo = (data) => request({
url: '/mobile/cjHzpAction!',
headers:{'Content-Type':'application/json'},
method: 'POST',
data: data
})
//字典
export const getDictionaries = (data) => request({
url: '/mobile/cjHzpAction!getCategory.do',
method: 'POST',
data: data
})
//初始化下拉框字典
export const initSelected = (data) => request({
url: '/mobile/cjHzpAction!to',
headers:{'Content-Type':'application/json'},
method: 'POST',
data: data
})
export const downLoadPdf = (data) => request({
url: '/mobile/cjHzpAction!PdfDownload.do',
headers:{'Content-Type':'application/json'},
method: 'POST',
data: data
})
5.在页面中引入 import js文件
6.封装请求调用方式
initList() { //调用方式 json参数这个是 具体去看第四步api的getlist
getlist(this.queryParamter).then(res => {
if (res.data.status == '200') {
this.responseData = res.data.data;
this.total = res.data.recordsTotal;
this.queryResult = true;
}
}).catch(err => {
console.log(err)
});
},
token的话 原理就是在3步骤里 请求登录接口后 后台给返回一个token 然后我们需要处理到本地存储里 uni.setStorageSync('accessToken', res.data.token); 这个方法
这样1步骤这里才可以拿到数据config.headers["accessToken"] = uni.getStorageSync('accessToken');
客户端设置token过期时间的话 我这里是存储token时 同时存储了一个时间戳 每次进行uni跳转时 判断当前时间时间戳有没有过期 过期的话就把token缓存和时间戳缓存一并清除 并携带参数 none 跳转到登陆页 登录页初始化判断参数进行动态返回状态 例如 未登录 用户信息已过期等
login的
创建 pages/router/index.js 拦截器 针对uni跳转进行拦截 时间问题 不是很完善 没写过的参考一下就行
(位置随便创建 只要最后在main.js中全局引用就行)
// 页面白名单 登录页面不拦截
const whiteList = [
'/pages/login/login',
]
function hasPermission(url) {
var timestamp = Date.parse(new Date());
const access_token = uni.getStorageSync('accessToken');
if(access_token == '') {//未登录
return 'notlogged'
}
// 在白名单中或有token,直接跳转
var timestampbeOverdue = uni.getStorageSync('timestampbeOverdue');
if (timestampbeOverdue <= timestamp) {
uni.clearStorageSync();
//弹窗提示 待解决 暂未解决
return 'none'
}
if (whiteList.indexOf(url) !== -1 || access_token != '') {
return true
}
return false
}
uni.addInterceptor('navigateTo', {
// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
invoke(e) {
if (hasPermission(e.url) == 'notlogged'){
uni.reLaunch({
url: '/pages/login/login?status=notlogged'
});
return false
}
if (hasPermission(e.url) == 'none') {
uni.reLaunch({
url: '/pages/login/login?status=none'
});
return false
}
if (!hasPermission(e.url)) {
uni.reLaunch({
url: '/pages/login/login?status=notlogged'
});
return false
}
return true
},
success(e) {
// console.log(e)
}
})
uni.addInterceptor('switchTab', {
// tabbar页面跳转前进行拦截
invoke(e) {
if (hasPermission(e.url)=='none'){
uni.reLaunch({
url: '/pages/login/login?status=none'
});
return false
}
if (hasPermission(e.url)=='notlogged') {
uni.reLaunch({
url: '/pages/login/login?status=notlogged'
});
return false
}
if (!hasPermission(e.url)) {
uni.reLaunch({
url: '/pages/login/login?status=notlogged'
});
return false
}
console.log('请求通过')
return true
},
success(e) {
console.log(e)
}
})
main.js引入
这种方式会有一个问题 只要不进行跳转 比如我输入url访问 那么这个拦截器就会失效 但是进入之后不携带token后台也请求不到 只能看到页面 这个时候解决方式就是在页面初始化上加上验证就行 不嫌麻烦的话 或者你再写个全局方法