Vue(9)vue-resource实现get,post,jsonp请求

vue-resource实现getpostjsonp请求

常见的数据类型:getpostjsonp
除了vue-resource(官方文档)之外,还可以使用axios(官方文档)使用第三方请求

配置vue-resource的步骤:
  • html文件中通过script标签引入 vue-resource文件;

    <script src="./lib/vue-2.4.0.js"></script>
    <script src="./lib/vue-resource-1.3.4.js"></script>
    

    注意:先引用vue文件,在引用vue-resource文件

  • get请求

    getInfo(){
    	this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
    		console.log(res.body);
    	 })
    }
    
  • post请求

    postInfo(){
    	var url = 'http://127.0.0.1:8899/api/post';
    	this.$http.post(url,{username:'zhangsan',pwd:'123456'},{emulateJSON:true}).then(res => {
    		console.log(res.body);
    		})
    }
    

    post 方法接收三个参数:

    • 参数1: 要请求的URL地址;
    • 参数2: 要发送的数据对象;
    • 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded;
  • jsonp请求

    this.$http.jsonp('http://127.0.0.1:8899/api/jsonp').then(res => {
    		console.log(res.body)
    })
    

    可以通过全局配置,设置BaseURL等参数,例如:

    	Vue.http.options.root = 'http://127.0.0.1:8899/'
    	// 全局启用 emulateJSON 选项
    	Vue.http.options.emulateJSON = true
    

    还可以在vue实例中配置:

    new Vue({
    	http: {
    		root : 'http://127.0.0.1:8899',
    	}
    })
    

注意:如果我们通过全局配置了,请求的数据接口根域名,则在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带/,否则不会启用根路径做拼接。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值