Vue-resource实现get,post,jsonp请求

Vue-resource

Vue-resource依赖于Vue,在引入时要先引入Vue文件,引入Vue-resource会在Vue实例中加一个属性this.$http.

全局配置数据接口的根域名

Vue.http.options.root = '/root';

私有配置数据接口的根域名

new Vue({
  http: {
    root: '/root'  
  }
})

全局配置emulateJSON选项

Vue.http.options.emulateJSON = true;

get请求

如果需要传递数据,可以使用 this.$http.get(‘url’,{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据

getInfo() { // get 方式获取数据
  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';
  // post 方法接收三个参数:
  // 参数1: 要请求的URL地址
  // 参数2: 要发送的数据对象,对象类型
  // 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
  this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
    console.log(res.body);
  });
}

jsonp请求

jsonpInfo() { // JSONP形式从服务器获取数据
  var url = 'http://127.0.0.1:8899/api/jsonp';
  this.$http.jsonp(url).then(res => {
    console.log(res.body);
  });
}

语法 & API

你可以使用全局对象方式 Vue.http 或者在一个 Vue 实例的内部使用 this.$http来发起 HTTP 请求。

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

vue-resource 提供了 7 种请求 API(REST 风格):

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

options 参数说明:

参数		类型							描述
url			string							请求的目标URL
body		Object, FormData, string		作为请求体发送的数据
headers		Object							作为请求头部发送的头部对象
params		Object							作为URL参数的参数对象
method		string							HTTP方法 (例如GETPOST...)
timeout		number							请求超时(单位:毫秒) (0表示永不超时)
before		function(request)				在请求发送之前修改请求的回调函数
progress	function(event)					用于处理上传进度的回调函数 ProgressEvent
credentials	boolean							是否需要出示用于跨站点请求的凭据
emulateHTTP	boolean							是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUTPATCHDELETE请求。
emulateJSON	boolean							设置请求体的类型为application/x-www-form-urlencoded

响应对象:

属性		类型					描述
url			string					响应的 URL 源
body		Object, Blob, string	响应体数据
headers		Header					请求头部对象
ok			boolean					当 HTTP 响应码为 200299 之间的数值时该值为 true
status		number					HTTP 响应码
statusText	string					HTTP 响应状态


方法		类型	描述
text()		约定值	以字符串方式返回响应体
json()		约定值	以格式化后的 json 对象方式返回响应体
blob()		约定值	以二进制 Blob 对象方式返回响应体
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值