当前位置: 首页 > news >正文

Vue:axios(POST请求)

基础 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);
    
http://www.xdnf.cn/news/614539.html

相关文章:

  • 【JavaScript 实现导航栏顶部吸附效果】
  • 8天Python从入门到精通【itheima】-35~37
  • 养成一个逐渐成长的强化学习ai
  • AI练习:折叠效果
  • magentic-ui和browser-use深度分析
  • 统一错误处理脚本实现
  • 数据赋能(234)——数据管理——标准化原则
  • CST软件基础六:视图
  • java中string类型的list集合放到redis的5种数据类型的那种比较合适呢,可以用StringRedisTemplate实现
  • 佰力博与您探讨PVDF薄膜极化特性及其影响因素
  • 巴西电商爆发期,第三方海外仓如何应用WMS系统抢占市场先机?
  • dubbo使用nacos作为注册中心配置
  • Python语法特点与编码规范
  • DAY 34 GPU训练及类的call方法
  • 设计模式——简单工厂模式
  • Zabbix实践!客户端自动发现
  • c++ constexpr关键字
  • VSCode如何像Pycharm一样“““回车快速生成函数注释文档?如何设置文档的样式?autoDocstring如何设置自定义模板?
  • RNN GRU LSTM 模型理解
  • 深度“求索”:DeepSeek+Dify构建个人知识库
  • SkyWalking高频采集泄漏线程导致CPU满载排查思路
  • RV1126 音频AI模块的详解
  • 树莓派4B搭建Hector SLAM算法, ROS1 ROS2?
  • 淘宝卖家评价等级如何区分?如何提升信誉等级?
  • 数据结构 -- 插入排序(直接插入排序和希尔排序)
  • 告别手抖困扰:全方位健康护理指南
  • React从基础入门到高级实战:React 基础入门 - 状态与事件处理
  • 量化交易新时代:Tick数据与股票API的完美融合
  • Python set集合方法详解
  • 无法选择最佳操作符(APP) 目录