vue05-axios网络请求

1.下载安装配置

1.文档结构
S-DB文件夹
------>db文件夹(用于连接数据库)
----->安装mongodb,
----->db-server.js
----->npm vue-axios axios
vue工程目录
----->vue.config.js
2.引入
在main.js中
import axios from ‘axios’
import VueAxios from “vue-axios”
Vue.config.productionTip = false

Vue.use(VueAxios,axios)
3.在vue.config.js中

module.exports={
    devServer:{
        port:'',
        open:true,
        proxy:'https://elm.cangdu.org',//配置开发服务器的代理
    }
}

2.发送请求

1.get请求
this指当前vue;
可换成Vue.axios.get(); 在main中import Vue from ‘vue’

this.axios.get('/v1/get',{params:{usr:this.usr,pwd:this.pwd}})
                    .then(response=>{
                    console.log(response.data)
                })
                    .catch(err=>{
                    console.log('请求错误:',err);
                });

2.post请求
post默认传输的是json格式(这是axios的特性),后台默认只接收键值对。
所以用qs转换一下
除非后台app.use(bp.json());//支持json

import qs from '../../node_modules/querystring'
this.axios.post('/v1/post',qs.stringify({usr:this.usr,pwd:this.pwd}))
                    .then(response=>{
                        console.log(response.data)
                    })
                    .catch(err=>{
                        console.log('请求错误:',err);
                    });

3.请求拦截

在main.js中

axios.interceptors.request.use(
    req=>{
      // console.log('将要给后台-------',req);
      //这里相当于中间站,所有不可以随便修改req,要继续返回给后台
      return req;
    }
)
axios.interceptors.response.use(
    res=>{
      // console.log('将要给前端--------',res);
      //拦截后台返回给前端的消息,可以稍做处理
      // 比如res.data,因为res还返回请求头之类的不需要的信息
      return res;
    }
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值