教程 axios tutorial

常见请求模板

在前端开发中,使用 Axios 封装和规范请求模板可以提升开发效率和可维护性。以下是常用的请求模板示例。

一、GET 请求

js
// 发送 GET 请求,带参数
axios.get('/api/user', { params: { id: 123 } })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

二、POST 请求

js
// 发送 POST 请求,提交 JSON 数据
axios.post('/api/user', { name: 'Alice', age: 25 })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

三、PUT 请求

js
// 更新资源
axios.put('/api/user/123', { name: 'Alice Updated' })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

四、DELETE 请求

js
// 删除资源
axios.delete('/api/user/123')
  .then(res => console.log('删除成功'))
  .catch(err => console.error(err));

五、结合 async/await

js
async function fetchUser(id) {
  try {
    const res = await axios.get(`/api/user`, { params: { id } });
    console.log(res.data);
  } catch (err) {
    console.error('请求失败:', err);
  }
}

六、带自定义请求头

js
axios.post('/api/user', { name: 'Bob' }, {
  headers: { Authorization: 'Bearer token' }
})
.then(res => console.log(res.data))
.catch(err => console.error(err));

七、小结

这些模板覆盖了前端常用的 HTTP 请求方式,结合 async/await 和自定义请求头,可以快速构建接口请求逻辑,并为后续封装通用请求模块打下基础。