当前位置:   article > 正文

vue2,3,小程序,uniapp的API请求封装统一管理请求接口_uniapp vue3 请求封装

uniapp vue3 请求封装

目录

 微信小程序

request.js

api.js页面 

页面使用 

 uniapp

request.js封装公共请求头

api.js里面存放api方法

在页面引入方法

vue2、3

request.js封装公共请求头

api.js文件

页面引入


 

 微信小程序

request.js

  1. // 引入env中的url
  2. const baseUrl = "http://www.com"; // 测试地址
  3. module.exports = {
  4. /**
  5. * url:请求的接口地址
  6. * method:请求方式 GET,POST....
  7. * data:要传递的参数
  8. */
  9. request: (obj) => {
  10. // console.log('这是我封装的ajax请求', baseUrl+obj.url);
  11. //这里使用ES6的写法拼接的字符串
  12. let _url = `${baseUrl}${obj.url}`;
  13. // console.log("请求信息",obj);
  14. return new Promise((resolve, reject) => {
  15. wx.showLoading({
  16. title: "正在加载",
  17. });
  18. wx.request({
  19. url: _url,
  20. data: obj.data,
  21. method: obj.method,
  22. header: {
  23. "content-type": "application/x-www-form-urlencoded",
  24. token: wx.getStorageSync("token"), //获取保存的token 项目请求接口需要token不需要就不写
  25. },
  26. success: (res) => {
  27. // console.log('从接口获取到的数据', res);
  28. resolve(res.data);
  29. wx.hideLoading();
  30. // wx.showToast({
  31. // icon: "none",
  32. // title: res.data.msg,
  33. // });
  34. },
  35. fail() {
  36. wx.hideLoading();
  37. reject("接口请求错误,请检查");
  38. },
  39. });
  40. });
  41. },
  42. };

api.js页面 

  1. //引入封装的reuest请求
  2. const {
  3. request
  4. } = require("./request.js");
  5. //基于业务封装的接口
  6. module.exports = {
  7. // 获取openid
  8. get_openidApi(data) {
  9. return request({
  10. url: "/api/wechat_notice/get_openid",
  11. method: "GET",
  12. method: "POST",
  13. data,
  14. });
  15. },
  16. // 登录操作
  17. loginApi(data) {
  18. return request({
  19. url: "/api/index/login",
  20. method: "POST",
  21. data,
  22. });
  23. },
  24. // 几天时间筛选
  25. time_arrayApi() {
  26. return request({
  27. url: "/api/index/time_array",
  28. method: "GET",
  29. });
  30. },
  31. };

页面使用 

引入

注意:微信小程序里面默认不能使用绝对路径,要使用../../../这样引入,层级过多不方便,建议配置绝对路径

微信小程序设置绝对路径方法

  1. const {
  2. loginApi,
  3. get_openidApi
  4. } = require('@/utils/api.js')

请求 

  1. login() {
  2. // 在登录事件里面请求这个接口
  3. if (this.data.account && this.data.password) {
  4. loginApi({
  5. account: this.data.account,
  6. password: this.data.password
  7. }).then((res) => {
  8. console.log(res);
  9. if (res.code == 1) {
  10. wx.setStorageSync('token', res.data.userinfo.token)
  11. wx.setStorageSync('account', this.data.account)
  12. wx.setStorageSync('password', this.data.password)
  13. // 登录成功 跳转到首页
  14. wx.switchTab({
  15. url: '/pages/index/index',
  16. })
  17. } else {
  18. Toast(res.msg);
  19. }
  20. })
  21. } else {
  22. Toast('请输入账号密码!');
  23. }
  24. },

 uniapp

request.js封装公共请求头

  1. /*
  2. @parms url 接口地址
  3. @parms method 请求方式
  4. @parms data 参数
  5. */
  6. const BASE_URL = "http://192.168.1.2:9999" //公共请求头地址
  7. const imgApi='http://kinggo.icu:7777/upload'// 上传接口
  8. const request = (url, method, data) => {
  9. let token = uni.getStorageSync('token') //token
  10. // console.log("token:", token);
  11. return new Promise((resolve, reject) => {
  12. uni.request({
  13. url: BASE_URL + url, // 开发者服务器接口地址
  14. method: method,//请求方式
  15. timeout: 60000, //请求超时时间
  16. data: data, //请求的参数
  17. header: { //设置请求的 header
  18. 'Content-Type': 'application/json',
  19. 'token': token, //自定义请求头信息token
  20. },
  21. success(res) { //对请求请求到的信息进行处理
  22. console.log(res.data)
  23. if (res.data.code == 200 || res.data.code == 500) {
  24. resolve(res.data)
  25. if (res.data.token) {//更新token
  26. uni.setStorageSync("token", res.data.token)
  27. }
  28. } else if (res.data.code == 600) {
  29. // uni.showToast({
  30. // title: '身份验证过期,请重新登录',
  31. // icon: 'none'
  32. // });
  33. uni.navigateTo({
  34. url: "/pages/login/login"
  35. })
  36. } else {
  37. // uni.showToast({
  38. // title: '请求失败,请重新获取数据',
  39. // icon: 'none'
  40. // });
  41. uni.navigateTo({
  42. url: "/pages/login/login"
  43. })
  44. }
  45. },
  46. fail(err) {
  47. reject(err)
  48. }
  49. })
  50. })
  51. }
  52. export default {
  53. request,imgApi //向外暴露request
  54. }

api.js里面存放api方法

  1. import request from './request.js' //引入request.js
  2. const api = request
  3. export default {
  4. // 手机号或id加密码登录
  5. getLogin: (username, password) => {
  6. let user = api.request('/logins', 'POST', {
  7. "po": username,
  8. "pwd": password,
  9. })
  10. .then(res => {
  11. // console.log(res); //正常的数据
  12. return res
  13. })
  14. return user
  15. },
  16. // 验证码登录
  17. codeLogin: (username, code) => {
  18. let user = api.request('/LoginRegister', 'get', {
  19. "po": username,
  20. "code": code,
  21. })
  22. .then(res => {
  23. // console.log(res); //正常的数据
  24. return res
  25. })
  26. return user
  27. }
  28. }

在页面引入方法

import Api from "@/API/api.js";

使用方法

  1. async login() {
  2. let user = await Api.codeLogin(this.username, this.password);
  3. }

vue2、3

request.js封装公共请求头

  1. import axios from 'axios'
  2. import {ElMessage} from 'element-plus'
  3. export const request = (options) => {
  4. return new Promise((resolve, reject) => {
  5. // create an axios instance
  6. const service = axios.create({
  7. // baseURL: process.env.BASE_API, // api 的 base_url
  8. baseURL: 'http://xxx.com',//测试地址
  9. timeout: 80000 // request timeout
  10. })
  11. // request interceptor
  12. service.interceptors.request.use(
  13. config => {
  14. if (sessionStorage.getItem('token')) {
  15. config.headers['token'] = sessionStorage.getItem('token')
  16. }
  17. return config
  18. },
  19. error => {
  20. // Do something with request error
  21. Promise.reject(error)
  22. }
  23. )
  24. // response interceptor
  25. service.interceptors.response.use(
  26. response => {
  27. return response.data
  28. },
  29. error => {
  30. if (error.response.data.code === 401) {
  31. ElMessage.error('请登录后在操作')
  32. setTimeout(function () {
  33. sessionStorage.clear()
  34. location.reload()
  35. }, 1000)
  36. }else if (error.response.data.code === 500){
  37. ElMessage.error('服务器请求错误,请稍后再试')
  38. }else{
  39. ElMessage.error('系统错误,请联系管理员')
  40. }
  41. return Promise.reject(error)
  42. }
  43. )
  44. // 请求处理
  45. service(options)
  46. .then((res) => {
  47. resolve(res)
  48. })
  49. .catch((error) => {
  50. reject(error)
  51. })
  52. })
  53. }
  54. export default request

api.js文件

  1. import {request} from '@/api/request'
  2. // 登录操作
  3. export function login(data) {
  4. return request({
  5. url: '/api/index/login',
  6. method: 'POST',
  7. data
  8. })
  9. }
  10. // 获取数据
  11. export function getBranchPosition() {
  12. return request({
  13. url: '/api/user/get_branch_position',
  14. method: 'GET'
  15. })
  16. }

页面引入

import {login, getBranchPosition} from "@/api";

 请求接口发起请求

  1. async function get_salary() {
  2. let res = await getBranchPosition({
  3. staff_id: staff_id.value,
  4. month_id: time_id.value,
  5. branch_id: branch_id.value
  6. })
  7. console.log(res.data);
  8. royaltyData.value = res.data.staff
  9. detailData.value = res.data.detail
  10. }

解构写法

  1. async function get_salary() {
  2. let staff_id= staff_id.value,
  3. let month_id= time_id.value,
  4. let branch_id= branch_id.value
  5. let res = await getBranchPosition({
  6. staff_id,
  7. month_id,
  8. branch_id
  9. })
  10. console.log(res.data);
  11. royaltyData.value = res.data.staff
  12. detailData.value = res.data.detail
  13. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/231259
推荐阅读
相关标签
  

闽ICP备14008679号