Vue js封装接口

天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/

1.安装axios

复制代码
npm install axios -g

2.在src下新建一个Api文件夹,再创建一个js文件

复制代码
import axios from 'axios'
let configuration = {
	url:"http://localhost:9090"
}
/**
 * 请求项目数据的请求体
 */
async function http({ url, method, param }) {
	const httpUrl = configuration.url + url
	if (method === 'GET') {
		httpUrl + jsonToGetParams(param)
	}
	const { data } = await axios({
		url: httpUrl,
		method: method ? method : 'GET',
		data: method === 'GET' ? {} : param,
		headers: {
			'content-type': 'application/json',
			token: localStorage.getItem('token') || ''
		}
	})
	return data
}
async function ask(e) {
	return http({
		url: e[0],
		method: e[1],
		param: e[2]
	})
}
export { ask }

/**
 * GET参数转字符串
 * @param jsonObj
 * @returns {string}
 */
function jsonToGetParams(jsonObj) {
	const params = Object.entries(jsonObj)
		.map(([key, value]) => `${key}=${value}`)
		.join('&')
	if (params.length >= 1) {
		return '?' + params
	} else {
		return params
	}
}

3.在src下新建一个Interface文件夹,里面单独存放接口,用户接口就创建UserApi.js文件,文件接口就创建FileApi.js

复制代码
import {ask} from "../Api/requestBody";

/**
 * 查询用户接口
 */
export function getQueryUser(param){
    return ask(['/user/queryUser','GET',param]);
}

4.来到vue页面调用

复制代码
 getQueryUserFun(){
      getQueryUser({
        id:"2222"
      }).then(res=>{
        console.log(res)
      })
    }
相关推荐
Pu_Nine_98 分钟前
10 分钟上手 ECharts:从“能跑”到“生产级”的完整踩坑之旅
前端·javascript·echarts·css3·html5
東雪蓮☆1 小时前
从零开始掌握 Web 与 Nginx:入门详解
运维·服务器·前端·nginx
脑子慢且灵1 小时前
【JavaWeb】一个简单的Web浏览服务程序
java·前端·后端·servlet·tomcat·web·javaee
柯南二号1 小时前
【大前端】 断点续传 + 分片上传(大文件上传优化) 的前端示例
前端
前端小超超1 小时前
如何配置capacitor 打包的安卓app固定竖屏展示?
android·前端·gitee
xiaopengbc1 小时前
在Webpack中,如何在不同环境中使用不同的API地址?
前端·webpack·node.js
前端AK君1 小时前
React中台系统如何嵌入到业务系统中
前端
Slice_cy1 小时前
不定高虚拟列表
前端
m0_748461392 小时前
Spring Boot + Vue 项目中使用 Redis 分布式锁案例
vue.js·spring boot·redis
前端AK君2 小时前
React组件库如何在vue项目中使用
前端