When you develop an application in Vue.js, data request interception and error handling are an integral part. By intercepting requests, you can modify them before sending them, and by error handling, you can efficiently handle error responses from the server. This article will introduce how to perform data request interception and error handling in Vue.js to ensure that your application has good stability and user experience.
1. Install and configure Axios
Before performing data request interception and error handling, first ensure that Axios has been installed and configured in your Vue.js project. Axios is a popular HTTP client for sending and receiving HTTP requests. You can install Axios using npm or yarn:
npm install axios
# 或者
yarn add axios
Then, you need to configure Axios into your Vue.js application. Typically, you would main.js
do this in a file:
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
2. Request interception
Request interception allows you to modify or add some information to the request before it is sent to the server, such as an authentication token. You can use Axios interceptors
to implement request interception. Here is an example:
// main.js
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
// 请求拦截器
axios.interceptors.request.use(
config => {
// 在请求发送前可以做一些操作,例如添加身份验证令牌
const token = localStorage.getItem('token')
if (token) {
config.headers.common['Authorization'] = `Bearer ${
token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
In the above code, we check whether the authentication token exists in the local storage through the request interceptor and add it in the request header.
3. Error handling
Error handling is a key part of ensuring your application has a good user experience when communicating with the server. You can use Axios interceptors
to globally capture error responses and take appropriate action. Here is an example:
// main.js
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
// 请求拦截器
axios.interceptors.request.use(
config => {
// 在请求发送前可以做一些操作,例如添加身份验证令牌
const token = localStorage.getItem('token')
if (token) {
config.headers.common['Authorization'] = `Bearer ${
token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
axios.interceptors.response.use(
response => {
// 对响应数据做一些处理
return response
},
error => {
// 全局错误处理
if (error.response) {
// 获取HTTP状态码
const status = error.response.status
if (status === 401) {
// 处理未授权的请求,例如重定向到登录页
router.push('/login')
} else if (status === 404) {
// 处理资源不存在的情况
router.push('/404')
} else {
// 其他错误处理逻辑
// ...
}
} else {
// 处理网络错误
// ...
}
return Promise.reject(error)
}
)
In the above code, we use response interceptor to handle error responses. If the server returns a 401 Unauthorized error, we can redirect the user to the login page. For other HTTP status codes, you can handle them appropriately as needed.
4. Using Axios in components
Now that you have configured Axios' request interception and error handling, you can easily use Axios to send HTTP requests in your Vue.js component. Here's a simple example:
<template>
<div>
<button @click="fetchData">获取数据</button>
<div v-if="data">{
{ data }}</div>
<div v-if="error">{
{ error }}</div>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
error: null
}
},
methods: {
fetchData() {
this.$http.get('/api/data')
.then(response => {
this.data = response.data
})
.catch(error => {
this.error = error.message
})
}
}
}
</script>
In the above example, we used in the component this.$http
to send the GET request and handle the success and failure cases.
5. Summary
Data request interception and error handling in Vue.js are important steps to ensure the stability of your application and user experience. By using Axios' interceptors, you can easily modify requests and handle error responses. Please customize interceptors and error handling logic according to your specific needs to ensure excellent performance and reliability of your Vue.js application.