Axios 是一个基于 Promise 的网络请求库。
安装
bash
npm install axios
引入
xml
<script setup>
import axios from 'axios'
</script>
常用 API
- axios.get(url[, config])
js
axios.get('/user',{
params: {
id: 1234,
}
})
.then(response => console.log(response))
.catch(error => console.log(error))
- axios.post(url[, data[, config]])
js
axios.post('/user',
{ // data
firstName: 'Fred',
lastName: 'Flintstone',
},
{ // config
headers: {
'Content-Type': 'application/json'
}
}
).then(response => console.log(response))
Vue3 项目中对 axios 封装
新建 utils/request.js 文件
js
import axios from "axios"
import { ElMessage } from 'element-plus'
const service = axios.create({
baseURL: '/api', // url = base url + request url
headers: {
"Content-Type": "application/json",
},
timeout: 5000,
})
// request 拦截器
service.interceptors.request.use(config => {
const timestamp = Date.now();
if (config.url){
config.url += `?timestamp=${timestamp}`
}
return config
})
// response 拦截器
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200){
ElMessage.error(res.message || "Error")
return Promise.reject(res)
}
return res
},
error => {
ElMessage.error(error),
return Promise.reject(error)
}
)
export default service