当前位置:   article > 正文

uni-app,vue3接口请求封装_vue3中引入request。js 封装api 接口请求

vue3中引入request。js 封装api 接口请求

uni-app接口,全局方法封装

1.在根目录创建一个api文件,在api文件夹中创建api.js,baseUrl.js和http.js文件

2. baseUrl.js文件代码

export default "https://XXXX.test03.qcw800.com/api/"

3.http.js文件代码

  1. export function https(opts, data) {
  2. let httpDefaultOpts = {
  3. url: opts.url,
  4. data: data,
  5. method: opts.method,
  6. header: opts.method == 'get' ? {
  7. 'X-Requested-With': 'XMLHttpRequest',
  8. "Accept": "application/json",
  9. "Content-Type": "application/json; charset=UTF-8"
  10. } : {
  11. 'X-Requested-With': 'XMLHttpRequest',
  12. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  13. },
  14. dataType: 'json',
  15. }
  16. let token = uni.getStorageSync('token');
  17. if (token != undefined && token != null && token != '') {
  18. httpDefaultOpts.header.Authorization = 'Bearer ' + token;
  19. }
  20. let promise = new Promise(function(resolve, reject) {
  21. uni.request(httpDefaultOpts).then(
  22. (res) => {
  23. // console.log(res, '成功')
  24. if(res.statusCode == 401){
  25. uni.clearStorageSync();
  26. }
  27. resolve(res)
  28. }
  29. ).catch(
  30. (response) => {
  31. // console.log(response, '失败')
  32. reject(response)
  33. }
  34. )
  35. })
  36. return promise
  37. }

4.api.js文件代码

  1. export const rootUrl="https://ssss.test03.qcw800.com"; //其他接口域名
  2. export const baseUrl= rootUrl + "api/";
  3. export const api = {
  4. // 获取验证码
  5. guest:{
  6. url: rootUrl + '/api/public/guest',
  7. method: 'GET'
  8. },
  9. // 登录
  10. login:{
  11. url: rootUrl + '/api/user/login',
  12. method: 'GET'
  13. }
  14. }

5.在main.js文件中引入接口文件

  1. import App from './App'
  2. // #ifndef VUE3
  3. import Vue from 'vue'
  4. Vue.config.productionTip = false; //设置为 false ,可以阻止 vue 在启动时生成生产提示
  5. App.mpType = 'app'
  6. const app = new Vue({
  7. ...App
  8. })
  9. app.$mount()
  10. // #endif
  11. // #ifdef VUE3
  12. import {
  13. createSSRApp
  14. } from 'vue'
  15. import {
  16. toast,
  17. nav,
  18. checkMobile,
  19. onuploadFile
  20. } from '@/api/functions.js'
  21. import {
  22. api,
  23. rootUrl
  24. } from '@/api/api.js' // API 链接
  25. import {
  26. https
  27. } from '@/api/http.js' // 请求方式中间件
  28. import navigationBar from '@/components/navigationBar.vue'
  29. import publicContext from '@/components/publicContext.vue'
  30. export function createApp() {
  31. const app = createSSRApp(App)
  32. app.component('navigationBar', navigationBar);
  33. app.component('publicContext', publicContext);
  34. app.config.globalProperties.$toast = toast;
  35. app.config.globalProperties.$nav = nav;
  36. app.config.globalProperties.$add = add;
  37. app.config.globalProperties.$checkMobile = checkMobile;
  38. app.config.globalProperties.$isEmpty = isEmpty;
  39. app.config.globalProperties.$formatFloat = formatFloat;
  40. app.config.globalProperties.$api = api;
  41. app.config.globalProperties.$rootUrl = rootUrl;
  42. app.config.globalProperties.$http = https;
  43. app.config.globalProperties.$imgUrl = 'https://qianchao-sheke.oss-cn-hangzhou.aliyuncs.com/'
  44. return {
  45. app
  46. }
  47. }
  48. // #endif

6.接口请求

  1. this.$http(this.$api.messageList,{
  2. api_token:uni.getStorageSync('token'),
  3. pageSize:10,
  4. page:1
  5. }).then(res=>{
  6. console.log(res,'返回参数');
  7. })
  8. //vue3,setup写法
  9. import { getCurrentInstance } from 'vue';
  10. const instance = getCurrentInstance();
  11. const { $http, $api } = instance.appContext.config.globalProperties;
  12. $http($api.messageList,{
  13. api_token:uni.getStorageSync('token'),
  14. pageSize:10,
  15. page:1
  16. }).then(res=>{
  17. console.log(res,'返回参数');
  18. })

另外,封装的全局方法,上面第五步在main文件中已经引入,

  1. export function toast(title){
  2. uni.showToast({
  3. icon:'none',
  4. title:title,
  5. position:'bottom',
  6. })
  7. }
  8. //校验手机格式
  9. export function checkMobile(mobile){
  10. return RegExp(/^1[34578]\d{9}$/).test(mobile);
  11. }
  12. export function nav(url,type=0){
  13. if(type == 0){
  14. uni.navigateTo({
  15. url:url
  16. })
  17. }else if(type == 1){
  18. uni.switchTab({
  19. url:url
  20. })
  21. }else if(type == 3){
  22. uni.navigateBack({
  23. })
  24. }else if(type == 4){
  25. uni.redirectTo({
  26. url: url
  27. });
  28. }else if(type == 5){
  29. uni.reLaunch({
  30. url
  31. });
  32. }
  33. }
  34. // 上传图片
  35. export function onuploadFile(){
  36. var _this = this;
  37. uni.chooseImage({
  38. count: 1, //默认9
  39. sizeType: ['original', 'compressed'],
  40. sourceType: ['album', 'camera'],
  41. success: (res) => {
  42. // console.log(res.tempFilePaths,'图片的本地文件路径列表',_this.$rootUrl);
  43. uni.uploadFile({
  44. url: _this.$rootUrl +'/api/public/upload',//上传图片的地址
  45. filePath: res.tempFilePaths[0],//这里是图片的本地文件路径列表(选择图片成功的时候可以拿到,在上边的success回调中res.tempFilePaths即可拿到)
  46. name: 'file',//上传的名字叫啥都行
  47. // headers: {
  48. // accessToken:'' //可以设置你的请求头的token噢
  49. // },
  50. success(res) {
  51. //上传成功的回调
  52. // console.log('上传成功',res)
  53. var data = JSON.parse(res.data);
  54. return data.data[0];
  55. },
  56. fail(err){
  57. console.log(err,'上传失败');
  58. },
  59. complete(result){
  60. console.log(result,'上传结果');
  61. }
  62. })
  63. }
  64. });
  65. }

vue3接口请求封装

1.在项目中安装axios

npm install --save axios vue-axios

2.在src文件夹下创建request文件夹,及index.js和api.js文件

3.index.js文件代码

  1. import axios from "axios";//创建一个axios的对象
  2. import { useRouter } from "vue-router";
  3. import { inject } from "vue";
  4. //生成一个axios的实例
  5. const http=axios.create({
  6. baseURL:"https://xxxx.test03.qcw800.com",// baseURL会在发送请求的时候拼接在url参数前面
  7. timeout:6000,//请求超时
  8. });
  9. // http.defaults.headers['api_token'] = localStorage.getItem('token') || '' //在请求头中传入token
  10. http.interceptors.request.use(config => {
  11. // console.log(config,'请求拦截');
  12. return config;
  13. }, err => {
  14. return Promise.reject(err)
  15. })
  16. //响应拦截器
  17. http.interceptors.response.use(response => {
  18. //console.log(response,'响应拦截');
  19. return response;
  20. }, err => {
  21. return Promise.reject(err)
  22. })
  23. export default http;//导出

 4.api.js文件代码

  1. //导入request.js
  2. import request from "@/request/index";
  3. //登录
  4. export const login = (params) => request.get("/api/user/login",{params});
  5. //获取个人信息
  6. export const userDetail = (params) => request.get("/api/user/detail",{params});
  7. //方法二 在api文件里出来异步请求
  8. // export const getCategory=async()=>{
  9. // const res=await request.get(`/category/`);
  10. // return res.data;
  11. // };

5.接口请求

  1. <script>
  2. import { defineComponent,onMounted } from 'vue'
  3. import { userDetail } from '@/request/api'
  4. export default defineComponent({
  5. setup() {
  6. onMounted(()=>{
  7. userDetail({api_token:localStorage.getItem('token')}).then(res=>{
  8. console.log(res,'个人信息');
  9. })
  10. })
  11. }
  12. })
  13. </script>

会了不!!

 等会还有解决跨域问题,代理代码

  1. const { defineConfig } = require('@vue/cli-service')
  2. module.exports = defineConfig({
  3. transpileDependencies: true,
  4. devServer: {
  5. port: 8080, // 端口号
  6. open: false, //配置是否自动启动浏览器
  7. https: false,// https:{type:Boolean}是否启用https
  8. proxy: {
  9. // 代理
  10. "/api": {
  11. target: "https://xxxx.test03.qcw800.com", //要代理访问的路径
  12. changeOrigin: true,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
  13. ws: true,//是否启用websockets,用不到可设为false
  14. pathRewrite: {
  15. "^/api": ""//这里理解成用'/api'代替target里面的地址,比如我要调用'http://192.168.0.45:8088/user/getuserlist',直接写'/api/user/getuserlist'即可
  16. }
  17. }
  18. }
  19. },
  20. })

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

闽ICP备14008679号