axios在Vue3中的使用实例代码
作者:velpro_!
Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js,这篇文章主要介绍了axios在Vue3中的使用,需要的朋友可以参考下
Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js。它可以在浏览器中发送异步请求,也可以在Node.js中发送HTTP请求。Axios可以处理HTTP请求和响应,支持拦截器、取消请求、自动转换JSON数据等功能。在Vue3中,Axios是一个常用的HTTP请求库。
1. 安装:npm install axios
2. 配置基础实例
// utils/http.js
import axios from "axios";
// 创建实例
 const httpInstance = axios.create({
     baseURL:'https://pcapi-xiaotuxian-front-devtest.itheima.net',
     timeout:5000
 })
// 如果项目里需要得到接口基地址不同,可以这样做
// axios.create()方法可以执行多次,每次执行就会生成一个新的实例
// const httpInstance2 = axios.create({
//     baseURL:'url2',  // 基地址
//     timeout:5000    // 超时器
// })
//拦截器
httpInstance.interceptors.request.use(config=>{
    return config
},e=>Promise.reject(e))
//响应器
httpInstance.interceptors.response.use(res=> res.data,e=>{
    return Promise.reject(e)
})
// 导出
export default httpInstance3.
// apis/testApi.js
import httpInstance from "@/utils/http";
export function getCatefory(){
    return httpInstance({
        url:'home/category/head'
    })
}4. 使用
import {getCatefory} from '@/apis/testApi'
getCatefory().then(res=>{
    console.log(res)
})到此这篇关于axios在Vue3中的使用的文章就介绍到这了,更多相关axios在Vue3使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
