1. 介绍
luch-request 是一个基于 Promise 开发的 uni-app 跨平台、项目级别的请求库。它具有更小的体积、易用的 API 和方便简单的自定义能力。luch-request 支持请求和响应拦截、全局挂载、多个全局配置实例、自定义验证器、文件上传/下载、任务操作、自定义参数以及多拦截器等功能。
2. 项目快速启动
安装
使用 npm 安装 luch-request:
npm install luch-request -S
创建实例
在项目中创建一个 request 实例(utils/request.js),并进行基本的配置:
request.js:
import Request from 'luch-request'
const baseUrl = 'http://192.168.1.167:8080/';
const http = new Request();
/** 设置全局配置 */
http.setConfig(config => {
config.baseURL = baseUrl;// 配置基础url
config.header = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
};
config.timeout = 15 * 1000;// 请求超时时间15s
return config
})
/** 请求之前拦截 */
http.interceptors.request.use(config => {
uni.showLoading({
title: '数据加载中...',
mask: true
});
// 设置5s中
setTimeout(function(){
uni.hideLoading()
},5000)
/* if (uni.getStorageSync('resToken')) {
config.header["Authorization"] = `Bearer ${uni.getStorageSync("resToken")}`;
} */
return config
},
error => {// 失败
return Promise.reject(error)
})
/** 响应拦截器 */
http.interceptors.response.use(response => {
console.log("response",response)
// 解析response.data中数据,根据返回值修改
const {
data,
success,
message,
token,
} = response.data
//console.log("message",message)
//console.log("success",success)
if (success) {
uni.hideLoading()
// 存储token到本地
uni.setStorageSync('resToken', token)
return response.data
}else{
uni.showToast({
//title: message,
title:"请求失败",
icon: 'error',
duration:2000,// 显示2s
})
uni.setStorageSync('resToken', null)
// 跳转回登录页面
uni.switchTab({
url: '/pages/login/login'
})
}
},
error =>{
// 对响应错误做点什么
return Promise.reject(error);
})
export default http;
3.创建请求方法
项目中创建api/api.js:
api.js:
import http from '@/utils/request.js'
// 获取用户信息-无参数
export function loginUser(){
return http.get('/api/loginUser.api')
}
// 登录post请求
export function LoginPostMethod(data) {
return http.post(
`/api/login.api?account=${data.account}&password=${data.password}`
)
}
// 登录post请求-Map<String, String>对象参数
export function LoginPostParamsMethod(data) {
// data 必须为对象
return http.post('/api/paramsLogin.api',data)
}
// 登录get请求
export function LoginGetMethod(data) {
return http.get(
`/api/login.api?account=${data.account}&password=${data.password}`
)
}
// 登录get请求-params参数 (只能get请求写params参数,post请求不能这么写报错)
export function LoginGetParamsMethod(data) {
return http.get(
'/api/paramsLogin.api',{
params: {
acc: data.account,
psw: data.password
}
}
)
}
// 箭头函数 - 修改密码
export const updatePassword = (data) =>{
return http.post('/api/updatePassword.api',data)
}
// 上传图片
/* export function upPhoto(data) {
return http.upload('app/inspection/inspectionPictureUploaded', {
filePath: data.file.path,
name: 'file',
params: {
inspectionId: data.inspectionId
}
}).then(res => {
console.log(res);
}).catch(err => {
console.error(err);
});
// return http.upload('api/upload/img', {
// files: [file], // 需要上传的文件列表
// name: 'file', // 文件对应的 key
// formData: {
// // 其他额外的 form data
// }
// }).then(res => {
// console.log(res);
// }).catch(err => {
// console.error(err);
// });
} */
4.使用方法
methods:{
async submit(){
// 无参数get请求
//const userInfo = await loginUser();
//console.log("userInfo",userInfo)
/**
* 默认账号:admin
* 默认密码:123
*/
// 模拟传递对象
const obj = {
account:"admin",
password:"123"
}
// 调用get请求
//const getResult = await LoginGetMethod(obj);
//console.log("getResult",getResult);
//param参数get请求
const getParamsResult = await LoginGetParamsMethod(obj);
console.log("getParamsResult",JSON.stringify(getParamsResult));
// 调用post请求
//const postResult = await LoginPostMethod(obj);
//console.log("postResult",JSON.stringify(postResult));
// Map<String, String>对象参数post请求
//const postParamsResult = await LoginPostParamsMethod(obj);
//console.log("postParamsResult",JSON.stringify(postParamsResult));
},
******
******
async jumpPage(data){// 跳转页面
const res = await updatePassword(data);
if(res.success){
uni.navigateBack({
url: '/pages/my/my'
});
}else{
uni.showToast({
title: "修改失败",
icon: "error"
})
}
},
***
***
submit(){
// 验证表单 (箭头函数异步方法)
this.$refs.loginForm.validate().then(async res=>{
console.log('验证通过',res);
/**
* 默认账号:admin
* 默认密码:123
*/
// 调用/store/index.js 中logIn方法
const result = await store.dispatch('logIn', res)
//console.log("result结果",result);
if(result.success){
setTimeout(function() {
uni.showToast({
title: '登录成功',
})
}, 800);
// 页面跳转
uni.reLaunch({
url: '/pages/index/index'
});
}
}).catch(err=>{
console.log('表单数据错误信息:', err);
/* uni.showToast({
title:'登录失败',
icon:'error',
}) */
});
},
}
5.后台代码(若依)
LoginController:
package com.ruoyi.api.login.controller;
import com.ruoyi.api.login.entity.User;
import com.ruoyi.api.login.response.ResponseData;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 移动端登录
* */
@RestController
@RequestMapping("/api")
public class LoginController {
/**
* GET请求无参数
* */
@GetMapping("/loginUser.api")
@ResponseBody
public ResponseData getLoginUser(){
System.out.println("无参数GET请求");
User user = new User();
user.setAccount("admin");
user.setPassword("123");
user.setToken("new_token");
user.setMessage("请求成功");
user.setSuccess(true);
return ResponseData.success(user);
}
/**
* GET请求
* 返回字符串
* */
@GetMapping("/login.api")
@ResponseBody
public ResponseData getLogin(String account, String password){
System.out.println("登录GET请求-------");
System.out.println("账号--"+account);
System.out.println("密码--"+password);
if ("admin".equals(account) && "123".equals(password)){
return ResponseData.success("get请求成功");
}
return ResponseData.error("get请求失败");
}
/**
* GET请求-params参数
* 返回字符串
*
* @ResponseBody
* 将方法返回值直接响应给浏览器
* 如果返回值类型是实体对象/集合,将会转换为JSON格式后在响应给浏览器
* */
@GetMapping("/paramsLogin.api")
@ResponseBody
public ResponseData getParamsLogin(@RequestParam(value = "acc") String account,
@RequestParam(value = "psw") String password){
System.out.println("登录GET请求params参数-------");
System.out.println("账号--"+account);
System.out.println("密码--"+password);
if ("admin".equals(account) && "123".equals(password)){
return ResponseData.success("GET请求params参数成功");
}
return ResponseData.error("GET请求params参数失败");
}
/**
* POST请求
* 返回对象
*
* @ResponseBody
* 将方法返回值直接响应给浏览器
* 如果返回值类型是实体对象/集合,将会转换为JSON格式后在响应给浏览器
* */
@PostMapping("/login.api")
public User postLogin(String account,String password){
System.out.println("登录POST请求-------");
System.out.println("账号--"+account);
System.out.println("密码--"+password);
// 创建模拟对象
User user = new User();
if ("admin".equals(account) && "123".equals(password)){
user.setAccount(account);
user.setPassword(password);
user.setToken("new_token");
user.setMessage("请求成功");
user.setSuccess(true);
return user;
}
user.setMessage("请求失败");
user.setSuccess(false);
return user;
}
/**
* 前端传递过来的参数必须为对象
* POST请求-Map<String, String>对象参数
* 返回ResponseData对象
* */
@RequestMapping(value = "/paramsLogin.api",method = RequestMethod.POST)
public ResponseData postParamsLogin(@RequestBody Map<String, String> body){
System.out.println("body"+body);
System.out.println("登录POST请求Map<String, String>对象参数-------");
System.out.println("账号--"+body.get("account"));
System.out.println("密码--"+body.get("password"));
String acc = body.get("account");
String psw = body.get("password");
// 创建模拟对象
User user = new User();
if ("admin".equals(acc) && "123".equals(psw)){
user.setAccount(acc);
user.setPassword(psw);
user.setToken("new_token");
user.setMessage("Map对象参数请求成功");
user.setSuccess(true);
return ResponseData.success(user);
}
return ResponseData.error("postMap对象请求失败");
}
/**
* 修改密码
* POST请求-Map<String, String>对象参数
* 返回ResponseData对象
* */
@PostMapping("/updatePassword.api")
public ResponseData updatePassword(@RequestBody Map<String,String> body){
System.out.println("修改密码POST请求Map<String, String>对象参数-------");
System.out.println("body"+body);
String oldPassword = body.get("oldPassword");
System.out.println("oldPassword:"+oldPassword);
String newPassword = body.get("newPassword");
System.out.println("newPassword:"+newPassword);
String confirmPassword = body.get("confirmPassword");
System.out.println("confirmPassword:"+confirmPassword);
// 创建模拟对象
User user = new User();
if("123".equals(oldPassword) && confirmPassword.equals(newPassword)){
user.setPassword(newPassword);
user.setToken("new_token");
user.setMessage("Map对象参数请求成功");
user.setSuccess(true);
return ResponseData.success(newPassword);
}
return ResponseData.error("修改失败");
}
}
User:
package com.ruoyi.api.login.entity;
import com.ruoyi.common.core.domain.BaseEntity;
public class User extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 编号 */
private Long tableId;
private String account;// 账号
private String password;// 密码
private String token;//token
private String message;// 信息
private Boolean success;// 是否成功
public Long getTableId() {
return tableId;
}
public void setTableId(Long tableId) {
this.tableId = tableId;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
}
响应对象
ErrorCodeEnum:
package com.ruoyi.api.login.response.enums;
public enum ErrorCodeEnum {
NOT_LOGIN(301, "请登录"),
PASS_LOGIN(301, "登录已超时,请重新登录");
private Integer code;
private String message;
private ErrorCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
}
ResponseData:
package com.ruoyi.api.login.response;
import com.ruoyi.api.login.response.enums.ErrorCodeEnum;
public class ResponseData {
public static final String DEFAULT_SUCCESS_MESSAGE = "请求成功";
public static final String DEFAULT_ERROR_MESSAGE = "网络异常";
public static final Integer DEFAULT_SUCCESS_CODE = 200;
public static final Integer DEFAULT_ERROR_CODE = 500;
private Boolean success;
private Integer code;
private String message;
private Object data;
public ResponseData() {
}
public ResponseData(Boolean success, Integer code, String message, Object data) {
this.success = success;
this.code = code;
this.message = message;
this.data = data;
}
public static SuccessResponseData success() {
return new SuccessResponseData();
}
public static SuccessResponseData success(Object object) {
return new SuccessResponseData(object);
}
public static SuccessResponseData success(Integer code, String message, Object object) {
return new SuccessResponseData(code, message, object);
}
public static ErrorResponseData error(String message) {
return new ErrorResponseData(message);
}
public static ErrorResponseData error(Integer code, String message) {
return new ErrorResponseData(code, message);
}
public static ErrorResponseData error(Integer code, String message, Object object) {
return new ErrorResponseData(code, message, object);
}
public static ResponseData error(ErrorCodeEnum errorCodeEnum) {
return error(errorCodeEnum.getCode(), errorCodeEnum.getMessage(), (Object)null);
}
public Boolean getSuccess() {
return this.success;
}
public Integer getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
public Object getData() {
return this.data;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public void setCode(Integer code) {
this.code = code;
}
public void setMessage(String message) {
this.message = message;
}
public void setData(Object data) {
this.data = data;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof ResponseData)) {
return false;
} else {
ResponseData other = (ResponseData)o;
if (!other.canEqual(this)) {
return false;
} else {
label59: {
Object this$success = this.getSuccess();
Object other$success = other.getSuccess();
if (this$success == null) {
if (other$success == null) {
break label59;
}
} else if (this$success.equals(other$success)) {
break label59;
}
return false;
}
Object this$code = this.getCode();
Object other$code = other.getCode();
if (this$code == null) {
if (other$code != null) {
return false;
}
} else if (!this$code.equals(other$code)) {
return false;
}
Object this$message = this.getMessage();
Object other$message = other.getMessage();
if (this$message == null) {
if (other$message != null) {
return false;
}
} else if (!this$message.equals(other$message)) {
return false;
}
Object this$data = this.getData();
Object other$data = other.getData();
if (this$data == null) {
if (other$data != null) {
return false;
}
} else if (!this$data.equals(other$data)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof ResponseData;
}
public int hashCode() {
boolean PRIME = true;
int result = 1;
Object $success = this.getSuccess();
result = result * 59 + ($success == null ? 43 : $success.hashCode());
Object $code = this.getCode();
result = result * 59 + ($code == null ? 43 : $code.hashCode());
Object $message = this.getMessage();
result = result * 59 + ($message == null ? 43 : $message.hashCode());
Object $data = this.getData();
result = result * 59 + ($data == null ? 43 : $data.hashCode());
return result;
}
public String toString() {
Boolean var10000 = this.getSuccess();
return "ResponseData(success=" + var10000 + ", code=" + this.getCode() + ", message=" + this.getMessage() + ", data=" + this.getData() + ")";
}
}
ErrorResponseData:
package com.ruoyi.api.login.response;
public class ErrorResponseData extends ResponseData{
private String exceptionClazz;
public ErrorResponseData(String message) {
super(false, ResponseData.DEFAULT_ERROR_CODE, message, (Object)null);
}
public ErrorResponseData(Integer code, String message) {
super(false, code, message, (Object)null);
}
public ErrorResponseData(Integer code, String message, Object object) {
super(false, code, message, object);
}
public String getExceptionClazz() {
return this.exceptionClazz;
}
public void setExceptionClazz(String exceptionClazz) {
this.exceptionClazz = exceptionClazz;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof ErrorResponseData)) {
return false;
} else {
ErrorResponseData other = (ErrorResponseData)o;
if (!other.canEqual(this)) {
return false;
} else {
Object this$exceptionClazz = this.getExceptionClazz();
Object other$exceptionClazz = other.getExceptionClazz();
if (this$exceptionClazz == null) {
if (other$exceptionClazz != null) {
return false;
}
} else if (!this$exceptionClazz.equals(other$exceptionClazz)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof ErrorResponseData;
}
public int hashCode() {
boolean PRIME = true;
int result = 1;
Object $exceptionClazz = this.getExceptionClazz();
result = result * 59 + ($exceptionClazz == null ? 43 : $exceptionClazz.hashCode());
return result;
}
public String toString() {
return "ErrorResponseData(exceptionClazz=" + this.getExceptionClazz() + ")";
}
}
SuccessResponseData:
package com.ruoyi.api.login.response;
public class SuccessResponseData extends ResponseData{
public SuccessResponseData() {
super(true, DEFAULT_SUCCESS_CODE, "请求成功", (Object)null);
}
public SuccessResponseData(Object object) {
super(true, DEFAULT_SUCCESS_CODE, "请求成功", object);
}
public SuccessResponseData(Integer code, String message, Object object) {
super(true, code, message, object);
}
}