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文件代码
export function https(opts, data) { let httpdefaultopts = { url: opts.url, data: data, method: opts.method, header: opts.method == 'get' ? { 'x-requested-with': 'xmlhttprequest', "accept": "application/json", "content-type": "application/json; charset=utf-8" } : { 'x-requested-with': 'xmlhttprequest', 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' }, datatype: 'json', } let token = uni.getstoragesync('token'); if (token != undefined && token != null && token != '') { httpdefaultopts.header.authorization = 'bearer ' + token; } let promise = new promise(function(resolve, reject) { uni.request(httpdefaultopts).then( (res) => { // console.log(res, '成功') if(res.statuscode == 401){ uni.clearstoragesync(); } resolve(res) } ).catch( (response) => { // console.log(response, '失败') reject(response) } ) }) return promise}
4.api.js文件代码
export const rooturl="https://ssss.test03.qcw800.com"; //其他接口域名export const baseurl= rooturl + "api/";export const api = { // 获取验证码 guest:{ url: rooturl + '/api/public/guest', method: 'get' }, // 登录 login:{ url: rooturl + '/api/user/login', method: 'get' }}
5.在main.js文件中引入接口文件
import app from './app'// #ifndef vue3import vue from 'vue'vue.config.productiontip = false; //设置为 false ,可以阻止 vue 在启动时生成生产提示app.mptype = 'app'const app = new vue({ ...app})app.$mount()// #endif// #ifdef vue3import { createssrapp} from 'vue'import { toast, nav, checkmobile, onuploadfile} from '@/api/functions.js'import { api, rooturl} from '@/api/api.js' // api 链接import { https} from '@/api/http.js' // 请求方式中间件import navigationbar from '@/components/navigationbar.vue'import publiccontext from '@/components/publiccontext.vue'export function createapp() { const app = createssrapp(app) app.component('navigationbar', navigationbar); app.component('publiccontext', publiccontext); app.config.globalproperties.$toast = toast; app.config.globalproperties.$nav = nav; app.config.globalproperties.$add = add; app.config.globalproperties.$checkmobile = checkmobile; app.config.globalproperties.$isempty = isempty; app.config.globalproperties.$formatfloat = formatfloat; app.config.globalproperties.$api = api; app.config.globalproperties.$rooturl = rooturl; app.config.globalproperties.$http = https; app.config.globalproperties.$imgurl = 'https://qianchao-sheke.oss-cn-hangzhou.aliyuncs.com/' return { app }}// #endif
6.接口请求
this.$http(this.$api.messagelist,{ api_token:uni.getstoragesync('token'), pagesize:10, page:1 }).then(res=>{ console.log(res,'返回参数'); })
另外,封装的全局方法,上面第五步在main文件中已经引入,
export function toast(title){ uni.showtoast({ icon:'none', title:title, position:'bottom', })}//校验手机格式 export function checkmobile(mobile){ return regexp(/^1[34578]\d{9}$/).test(mobile);}export function nav(url,type=0){ if(type == 0){ uni.navigateto({ url:url }) }else if(type == 1){ uni.switchtab({ url:url }) }else if(type == 3){ uni.navigateback({ }) }else if(type == 4){ uni.redirectto({ url: url }); }else if(type == 5){ uni.relaunch({ url }); }}// 上传图片export function onuploadfile(){ var _this = this; uni.chooseimage({ count: 1, //默认9 sizetype: ['original', 'compressed'], sourcetype: ['album', 'camera'], success: (res) => { // console.log(res.tempfilepaths,'图片的本地文件路径列表',_this.$rooturl); uni.uploadfile({ url: _this.$rooturl +'/api/public/upload',//上传图片的地址 filepath: res.tempfilepaths[0],//这里是图片的本地文件路径列表(选择图片成功的时候可以拿到,在上边的success回调中res.tempfilepaths即可拿到) name: 'file',//上传的名字叫啥都行 // headers: { // accesstoken:'' //可以设置你的请求头的token噢 // }, success(res) { //上传成功的回调 // console.log('上传成功',res) var data = json.parse(res.data); return data.data[0]; }, fail(err){ console.log(err,'上传失败'); }, complete(result){ console.log(result,'上传结果'); } }) } });}
vue3接口请求封装1.在项目中安装axios
npm install --save axios vue-axios
2.在src文件夹下创建request文件夹,及index.js和api.js文件
3.index.js文件代码
import axios from "axios";//创建一个axios的对象import { userouter } from "vue-router";import { inject } from "vue";//生成一个axios的实例const http=axios.create({ baseurl:"https://xxxx.test03.qcw800.com",// baseurl会在发送请求的时候拼接在url参数前面 timeout:6000,//请求超时});// http.defaults.headers['api_token'] = localstorage.getitem('token') || '' //在请求头中传入tokenhttp.interceptors.request.use(config => { // console.log(config,'请求拦截'); return config;}, err => { return promise.reject(err)})//响应拦截器http.interceptors.response.use(response => { //console.log(response,'响应拦截'); return response; }, err => { return promise.reject(err) })export default http;//导出
4.api.js文件代码
//导入request.jsimport request from "@/request/index";//登录export const login = (params) => request.get("/api/user/login",{params});//获取个人信息export const userdetail = (params) => request.get("/api/user/detail",{params});//方法二 在api文件里出来异步请求// export const getcategory=async()=>{// const res=await request.get(`/category/`);// return res.data;// };
5.接口请求
<script>import { definecomponent,onmounted } from 'vue'import { userdetail } from '@/request/api'export default definecomponent({ setup() { onmounted(()=>{ userdetail({api_token:localstorage.getitem('token')}).then(res=>{ console.log(res,'个人信息'); }) }) }})</script>
会了不!!
等会还有解决跨域问题,代理代码
const { defineconfig } = require('@vue/cli-service')module.exports = defineconfig({ transpiledependencies: true, devserver: { port: 8080, // 端口号 open: false, //配置是否自动启动浏览器 https: false,// https:{type:boolean}是否启用https proxy: { // 代理 "/api": { target: "https://xxxx.test03.qcw800.com", //要代理访问的路径 changeorigin: true,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题 ws: true,//是否启用websockets,用不到可设为false pathrewrite: { "^/api": ""//这里理解成用'/api'代替target里面的地址,比如我要调用'http://192.168.0.45:8088/user/getuserlist',直接写'/api/user/getuserlist'即可 } } } },})
以上就是uni-app vue3接口请求怎么封装的详细内容。