跳到主要内容

添加网络请求库 Axios

视频演示

环境准备
  • 安装 Git
    • 设置换行符为 lf
    $ git config --global core.autocrlf input
    $ git config --global core.eol lf
  • 安装 Node.js
  • 安装 VSCode

拉取项目

# 从 GitHub 拉取项目(存在网络限制)
$ git clone --branch v0.0.5 https://github.com/geenln/vue3-elemnt-plus-ts.git

# 或者从 Gitee 拉取项目
$ git clone --branch v0.0.5 https://gitee.com/genin/vue3-elemnt-plus-ts.git

安装项目依赖

$ npm install

启动开发服务器

$ npm run dev

添加请求库 Axios

添加 Axios

安装 Axios

$ npm install axios

创建文件 src/common/http.ts

src/common/http.ts
import axios from 'axios'
import {ElMessage} from 'element-plus'
import 'element-plus/es/components/message/style/css'

const instance = axios.create({
baseURL: '',
timeout: 20000,
})

instance.interceptors.request.use(
config => {
// TODO: 添加请求参数
// 例如:统一添加请求 token
config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
return config
},
error => {
return Promise.reject(error)
},
)

instance.interceptors.response.use(
response => {
// TODO: 处理请求响应
// 例如:统一处理错误信息
if (response.data && !response.data.success) {
ElMessage.error('请求失败')
return Promise.reject(response.data)
}
return response.data
},
error => {
return Promise.reject(error)
},
)

export default instance

更新文件 src/App.vue 查看效果

src/App.vue
<script setup lang="ts">
//...
+import http from '@/common/http'

//...
+const baseUrl = 'https://mock.presstime.cn/mock/6655e837dd3831604fff689f/example'
+const handleRequest = (type: string) => {
+ if ('normal' === type) {
+ http.get(`${baseUrl}/normal`).then(res => {
+ console.info('normal: ', res)
+ })
+ }

+ if ('failed' === type) {
+ http.get(`${baseUrl}/failed`).then(res => {
+ console.info('failed: ', res)
+ }).catch(error => {
+ console.error('error: ', error)
+ })
+ }
+}
</script>

<template>
//...

+ <ElButton @click="handleRequest('normal')"> 正常请求 </ElButton>

+ <ElButton @click="handleRequest('failed')"> 失败请求 </ElButton>

//...
</template>