当前位置: 首页 > article >正文

uniapp luch-request 使用教程+响应对象创建

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) {
	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"
					}) 
				}
			
				
				
			},
}

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);
    }

}


http://www.kler.cn/a/395209.html

相关文章:

  • 从python源码到可自动更新软件
  • 51c嵌入式~单片机合集2
  • 单片机设计电流与温度监控python上位机监控平台设计
  • 开源模型应用落地-qwen模型小试-Qwen2.5-7B-Instruct-tool usage入门-集成心知天气(二)
  • MySQL —— MySQL逻辑架构与查询过程
  • git入门环境搭建
  • 异步处理之async/await使用技巧分享
  • 【广西-柳州】《柳州市本级信息化建设项目预算支出标准(试行)》(柳财审〔2020〕16号 )-省市费用标准解读系列11
  • Windows搭建流媒体服务并使用ffmpeg推流播放rtsp和rtmp流
  • 【redis】redis
  • c# 在10万条数据中判断是否存在很慢问题
  • 【金猿案例展】科技日报——大数据科技资讯服务平台
  • DB-GPT系列(五):DB-GPT六大基础应用场景part2
  • pyinstaller+upx给python GUI程序添加自定义图标
  • 驾校增加无人机培训项目可行性技术分析
  • 本地搭建你的私有网盘:在Ubuntu上使用Portainer CE安装NextCloud
  • 基于springboot+vue实现的高校电子图书馆的大数据平台 (源码+L文+ppt)4-013
  • Jmeter中的配置原件(四)
  • 机器学习周报(transformer学习1)
  • PG数据库 数据库时间字段 开始时间和结束时间,判断和查询条件的开始和截止时间存在交集,SQL如何编写
  • vue请求数据报错,设置支持跨域请求,以及2种请求方法axios或者async与await
  • golang反射函数注册
  • (十六)JavaWeb后端开发——Spring框架常见注解
  • 【C++】C++基础知识
  • 翼鸥教育:从OceanBase V3.1.4 到 V4.2.1,8套核心集群升级实践
  • 使用 Python 向 IP 地址发送字符串 —— TCP 与 UDP 协议详解