How to use axios to make Ajax request in Vue3?

In the development of modern web applications, it is often necessary to use Ajax technology to interact with the server to obtain data, send requests or update data, etc. Vue3 is a popular JavaScript framework that provides us with many tools and libraries to simplify and optimize communication with the server. One of the commonly used tools is axios, which is a Promise-based HTTP client that can send HTTP requests in the browser and Node.js. This article will introduce in detail the methods and techniques of using axios to make Ajax requests in Vue3.

install axios

To use axios in Vue3, you first need to install the axios package. You can install axios using npm or yarn:

npm install axios

or

yarn add axios

After the installation is complete, you can introduce axios into your project and start using it for Ajax requests.

Send a GET request

Sending GET requests with axios is very easy. Just call the axios getmethod, passing the URL as a parameter. For example, we want to get a userslist of users named:

import { ref } from 'vue'
import axios from 'axios'

const getUsers = async () => {
  try {
    const response = await axios.get('https://api.example.com/users')
    return response.data
  } catch (error) {
    console.error(error)
  }
}

export default {
  setup() {
    const users = ref([])
    
    getUsers().then(data => {
      users.value = data
    })
    
    return {
      users
    }
  }
}

In the above code, we first introduced refthe functions and axios of Vue3. Then, we define an getUsersasynchronous function named . This function sends a GET request to https://api.example.com/usersand returns the response data.

In setupthe function, we create a reactive object called usersand refcall getUsersthe function to get the user list data. Once the data is returned, we save it into usersan object.

Send a POST request

Similar to sending GET requests, sending POST requests with axios is also very simple. Just call postthe method of axios and pass the URL and request data as parameters. For example, we want to create a new user:

import axios from 'axios'

const createUser = async (user) => {
  try {
    const response = await axios.post('https://api.example.com/users', user)
    return response.data
  } catch (error) {
    console.error(error)
  }
}

export default {
  setup() {
    const handleCreateUser = async () => {
      const newUser = { name: 'John Doe', email: '[email protected]' }
      const createdUser = await createUser(newUser)
      console.log(createdUser)
    }

    return {
      handleCreateUser
    }
  }
}

In the above code, we defined an createUserasynchronous function called . This function sends a POST request to https://api.example.com/usersand passes the user data to be created as a parameter.

In setupfunctions, we create a handleCreateUserfunction called . When called handleCreateUser, it creates a new user and prints the created user data to the console.

error handling

We have to think about error handling when sending requests to the server. Axios provides a mechanism for catching errors, and you can use the try-catch statement to handle errors that occur during the request.

try {
  const response = await axios.get('https://api.example.com/users')
  return response.data
} catch (error) {
  console.error(error)
}

In the above code, we use try-catch statement to catch errors. If an error occurs during the request, an error message will be output to the console.

You can also perform specific actions based on different error types. For example, if the server returns a 404 error, you can implement some specific error handling logic:

try {
  const response = await axios.get('https://api.example.com/users')
  return response.data
} catch (error) {
  if (error.response.status === 404) {
    console.log('User not found')
  } else {
    console.error(error)
  }
}

In the above code, we check the value responseof the property of the error object status. If the value is 404, it means the user is not found, and "User not found" will be printed on the console. Otherwise, an error message will be printed.

Request Interceptor and Response Interceptor

Axios also provides request interceptors and response interceptors to process requests and responses before the request is sent and after the response is returned.

axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  console.log('Before request')
  return config
}, error => {
  // 对请求错误做些什么
  console.error(error)
  return Promise.reject(error)
})

In the above code, we axios.interceptorsset the request interceptor through the object. request.useThe method receives two callback functions, the first one is used to handle the logic before the request is sent, and the second one is used to handle the request error.

Similarly, we can also set response interceptors:

axios.interceptors.response.use(response => {
  // 对响应数据做点什么
  console.log('After response')
  return response
}, error => {
  // 对响应错误做点什么
  console.error(error)
  return Promise.reject(error)
})

In the above code, we axios.interceptorsset the response interceptor through the object. response.useThe method receives two callback functions, the first one is used to handle the logic after the response is returned, and the second one is used to handle the response error.

Interceptors can be used to add request headers before the request is sent, and process the response data after the response is returned. For example, we can add an authentication token to every request header:

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  console.error(error)
  return Promise.reject(error)
})

In the above code, we get the token from localStorage and add it to Authorizationthe field in the request header.

Summarize

This article introduces in detail the methods and techniques of using axios to make Ajax requests in Vue3. We discussed how to install the axios package, send GET and POST requests, and how to handle errors, use interceptors, and more.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131813655
Recommended