# Axios 四种常见操作总结

Axios 是一个基于 Promise 的 HTTP 客户端,可以用于浏览器和 Node.js 发起请求。以下是 putpostgetdelete 四种常见的操作方式。

# GET 请求

用于从服务器获取资源。

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response.data); // 服务器返回的数据
    console.log(response.status); // 状态码
  })
  .catch(function (error) {
    console.error(error);
  });

或者使用 async/await:

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

# POST 请求

用于向服务器提交数据。

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response.data); // 服务器响应的数据
  })
  .catch(function (error) {
    console.error(error);
  });

使用 async/await 形式:

async function createUser() {
  try {
    const response = await axios.post('/user', {firstName: 'Fred', lastName: 'Flintstone'});
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

# PUT 请求

用于更新已有资源,通常需要传递整个对象来替换现有资源。

axios.put('/user/12345', {
    firstName: 'Fred',
    lastName: 'Flintstone',
    email: 'fred@example.com'
  })
  .then(function (response) {
    console.log(response.data); // 更新后的资源信息
  })
  .catch(function (error) {
    console.error(error);
  });

使用 async/await 版本:

async function updateUser() {
  try {
    const response = await axios.put('/user/12345', {firstName: 'Fred', lastName: 'Flintstone', email: 'fred@example.com'});
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

# DELETE 请求

用于删除资源。

axios.delete('/user/12345')
  .then(function (response) {
    console.log("Deleted successfully"); // 成功消息或状态
  })
  .catch(function (error) {
    console.error(error);
  });

使用 async/await 形式:

async function deleteUser() {
  try {
    const response = await axios.delete('/user/12345');
    console.log("Deleted successfully");
  } catch (error) {
    console.error(error);
  }
}
更新于 阅读次数