赞
踩
以vite创建的项目,vue3使用axios,使用ts二次封装axios访问接口,并调用接口。
npm install axios
在使用的文件中引入
import axios from "axios";
request.ts
- import axios from "axios";
- import { ElMessage } from 'element-plus'
- const service = axios.create({
- baseURL: import.meta.env.VITE_BASE_URL, // url = base url + request url
- timeout: 30000,// request timeout
- // withCredentials:true
- })
- // 请求拦截
- service.interceptors.request.use(
- (config: any) => {
- return config
- },
- (error: any) => {
- return Promise.reject(error)
- }
- )
-
- // 响应拦截
- service.interceptors.response.use(
- (response: any) => {
- const res = response.data
- if (res.code !== 1 || res.code !== 200) {
- return response.data
- } else {
- return response.data
- }
- },
- (error: any) => {
- if (error.response) {
- switch (error.response.status) {
- case 500:
- ElMessage({
- message: "服务器错误,请稍后重试",
- type: "error",
- duration: 5 * 1000
- })
- break
- default:
- if (error.response.data.error == "invalid_grant") {
- ElMessage({
- message: error.response.data.error_description,
- type: "error"
- })
- }
- return Promise.reject(error)
- }
- }
- }
- )
-
- export default service
api.ts
- import request from "@/utils/request";
-
- export function getUniteLoginUrl(params: any) {
- return request({
- url: '/portal/user/getUniteLoginUrl',
- method: 'post',
- params
- })
- }
需要调用api接口的文件,此为ts setup语法糖模式
- import {getUniteLoginUrl} from "@/api/api"
- import { onMounted } from "vue";
-
- onMounted(()=>{
- getUniteLoginUrl({type:'0'}).then((res: any)=>{
- console.log(res,"res====");
-
- })
- })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。