Vue数据请求axios和fetch
数据请求有两种形式
1.使用原生JavaScript提供的数据请求
(1)ajax
需结合Promise去封装,效率高但是不便利
(2)fetch
本身结合了Promise且已封装好,可直接使用
2.使用第三方库
axios:目前最流行,使用率最高
3.vue2.x版本常用的数据请求为axios和fetch
数据请求类型有
get, post, put, delete, option, head, ....
Axios总结
axios得到的结果会进行一层封装
{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data: 3 headers: {content-type: "text/html; charset=UTF-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" __proto__: Object
1.get方法
(1)无参数
axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
(2)有参数
login(){ axios.get('http://localhost:9090/user/login', { // 传递的参数 params: { account:this.formLogin.account, password:this.formLogin.password, testParam:'hello world' } // 回调函数,一定要使用箭头函数,不然this的指向不是vue示例 }).then(res =>{ // 如果状态为400,说明登录失败 if(res.data.status===400){ // 登录失败提示 this.$message({showClose: true, message: '登录失败,请检查账号和密码!',type: 'error', duration:2000,center:true}); }else{ // 登录成功提示 this.$message({showClose: true, message: '登录成功!',type: 'success', duration:2000,center:true}); // 跳转到首页路由 this.$router.push("/main/home"); } }).catch(error =>{ console.log(error) }) },
2.post方法
先设置请求头,然后实例化URLSearchParams的构造器函数得到params对象,最后使用params对象的append方法进行数据传参
// 统一设置请求头 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; let params = new URLSearchParams() // params.append(key,value) params.append('a',1) params.append('b',2) axios({ url: 'http://localhost:9090/user/save', method: 'post', data: params, headers: { //单个请求设置请求头 'Content-Type': "application/x-www-form-urlencoded" } }).then(res => { console.log( res ) }).catch( error => { if( error ){ throw error } })
参考链接:
https://www.cnblogs.com/zhaoyingzi/p/10920074.html
分类:
前端 / vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义