Vue:axios(POST请求)

发布于:2025-05-24 ⋅ 阅读:(21) ⋅ 点赞:(0)

基础 POST 请求

// 简单表单提交
axios.post('/api/login', {
  username: 'lcyyyy',
  password: '123456'
})
.then(response => {
  console.log('登录成功:', response.data);
});

发送 JSON 数据

axios.post('/api/users', {
  name: '来财羊',
  age: 18
}, {
  headers: {
    'Content-Type': 'application/json' // 默认可省略
  }
});

发送 FormData(文件上传)

<input type="file" @change="uploadFile">

<script>
methods: {
  uploadFile(event) {
    const file = event.target.files[0];
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('userId', 123);

    axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
}
</script>

URL 编码格式

import qs from 'qs';

axios.post('/api/login', qs.stringify({
  username: 'lcyyyy',
  password: '123456'
}), {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

高级配置选项

axios.post('/api/data', payload, {
  timeout: 10000, // 10秒超时
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Authorization': `Bearer ${localStorage.token}`
  },
  onUploadProgress: progressEvent => {
    // 上传进度处理
    const percent = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    console.log(`上传进度: ${percent}%`);
  }
});

完整请求生命周期处理

async submitForm() {
  this.loading = true;
  this.error = null;

  try {
    const response = await axios.post('/api/orders', this.formData);
    
    // 处理成功响应
    if (response.data.success) {
      this.$router.push('/success');
      this.$notify({
        type: 'success',
        message: '订单创建成功'
      });
    }
  } catch (error) {
    // 错误分类处理
    if (error.response) {
      switch (error.response.status) {
        case 400:
          this.error = '请求参数错误';
          break;
        case 401:
          this.$store.dispatch('logout');
          break;
        case 500:
          this.error = '服务器错误,请稍后重试';
          break;
        default:
          this.error = '请求失败';
      }
    } else if (error.request) {
      this.error = '网络连接异常';
    } else {
      this.error = '请求配置错误';
    }
  } finally {
    this.loading = false;
  }
}

数据验证
前端做基础验证,后端做最终验证:

if (!this.formData.email.includes('@')) {
  alert('邮箱格式错误');
  return;
}
  1. 请求重试机制

    async function postWithRetry(url, data, retries = 3) {
      try {
        return await axios.post(url, data);
      } catch (err) {
        if (retries > 0 && err.code !== 'ECONNABORTED') {
          await new Promise(resolve => setTimeout(resolve, 2000));
          return postWithRetry(url, data, retries - 1);
        }
        throw err;
      }
    }
    
  2. 批量请求处理

    const requests = items.map(item => 
      axios.post('/api/items', item)
    );
    
    const results = await Promise.allSettled(requests);
    const successfulItems = results
      .filter(r => r.status === 'fulfilled')
      .map(r => r.value.data);
    

网站公告

今日签到

点亮在社区的每一天
去签到