vue-resource post php,Vue学习笔记进阶篇——vue-resource安装及使用

简介

vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。也就是说,$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的API更为简洁。

本文是基于之前的文章(Vue学习笔记进阶篇——vue-cli安装及介绍)vue-cli脚手架工具的。

基本语法

引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用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);

以下是一个简单的get使用示例:

// GET /someUrl

this.$http.get('/someUrl').then(response => {

// success callback

}, response => {

// error callback

});

http方法列表

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

Parameter

Type

Description

url

string

URL to which the request is sent

body

Object, FormData, string

Data to be sent as the request body

headers

Object

Headers object to be sent as HTTP request headers

params

Object

Parameters object to be sent as URL parameters

method

string

HTTP method (e.g. GET, POST, ...)

responseType

string

Type of the response body (e.g. text, blob, json, ...)

timeout

number

Request timeout in milliseconds (0 means no timeout)

before

function(request)

Callback function to modify the request options before it is sent

progress

function(event)

Callback function to handle the ProgressEvent of uploads

credentials

boolean

Indicates whether or not cross-site Access-Control requests should be made using credentials

emulateHTTP

boolean

Send PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header

emulateJSON

boolean

Send request body as application/x-www-form-urlencoded content type

Response

返回对象的参数以及对象的方法如下:

Property

Type

Description

url

string

Response URL origin

body

Object, Blob, string

Response body

headers

Header

Response Headers object

ok

boolean

HTTP status code between 200 and 299

status

number

HTTP status code of the response

statusText

string

HTTP status text of the response

Method

Type

Description

text()

Promise

Resolves the body as string

json()

Promise

Resolves the body as parsed JSON object

blob()

Promise

Resolves the body as Blob object

Example

简单的post提交

{

// POST /someUrl

this.$http.post('/someUrl', {foo: 'bar'}).then(response => {

// get status

response.status;

// get status text

response.statusText;

// get 'Expires' header

response.headers.get('Expires');

// get body data

this.someData = response.body;

}, response => {

// error callback

});

}

带查询参数和自定义请求头的GET请求

{

// GET /someUrl?foo=bar

this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '...'}}).then(response => {

// success callback

}, response => {

// error callback

});

}

获取图片并使用blob()方法从响应中提取图片的主体内容。

// GET /image.jpg

this.$http.get('/image.jpg', {responseType: 'blob'}).then(response => {

// resolve to Blob

return response.blob();

}).then(blob => {

// use image Blob

});

安装

在终端通过cd命令进入到之前文章中创建的my-demo1项目目录里,然后使用以下命令进行安装:

npm install vue-resource --save

--save参数的作用是在我们的包配置文件package.json文件中添加对应的配置。安装成功后, 可以查看package.json文件,你会发现多了"vue-resource": "^1.3.4"的配置。具体如下:

"dependencies": {

"vue": "^2.3.3",

"vue-resource": "^1.3.4",

"vue-router": "^2.7.0"

},

使用

注册

通过以上步骤,我们已经安装好了vue-resource,但是在vue-cli中我们如何使用呢?

首先,我们需要在main.js文件中导入并注册vue-resource:

import VueResource from 'vue-resource'

Vue.use(VueResource)

项目中调用

在此之前,我用php的laravel框架开发了一些简单的api接口,用以接下来我们的测试。这里我先介绍下,我的api接口的功能:

url: http://api.chairis.cn/api?app_id=123456&method=demo.run

params:

app_id: 应用id, 我这边提供了一个测试的id123456

method: 方法名称,我这边提供的测试方法为demo.run

功能:这个方法的功能就比较简单了,就是把上送的参数再返回来而已。

我们可以在浏览器中输入上述url测试下是否能成功:

937897b65d46

从图中可以看出,返回的对象里,data就是我们的上送的内容,当然你也可以加一些其他的参数,也同样的会返回,只是app_id, method必须是正确的,其他的随便。如下:

937897b65d46

既然我们的接口是没有问题的,那么,我们就试试我们的vue-resource的强大功能吧。这里我们就在之前的DemoHome组件里实现我们的测试吧。

get

修改DemoHome组件的javascript标签的代码如下:

export default({

name:'home',

mounted:function () {

this.$http.get('http://api.chairis.cn/api',{

params:{

app_id:'123456',

method:'demo.run',

name:'chain'

}

}).then(response => {

console.log('请求成功')

},

response => {

console.log('请求失败')

});

}

})

保存后,刷新页面,可以从控制台看到输出了请求成功字样。然后我们再看下请求和返回的数据:

请求:

937897b65d46

响应:

937897b65d46

post

修改DemoHome组件的javascript标签的代码如下:

export default({

name:'home',

mounted:function () {

this.$http.post('http://api.chairis.cn/api?app_id=123456&method=demo.run',{

body: {

name: {

first_name: 'chain',

last_name: 'zhang'

},

email: 'zzceng@126.com'

}

},{emulateJSON: true}).then(response => {

console.log('请求成功')

},

response => {

console.log('请求失败')

});

}

})

保存后,刷新页面,可以从控制台看到输出了请求成功字样。然后我们再看下请求和返回的数据:

请求:

937897b65d46

响应:

937897b65d46

在这里我们看到了陌生的东西emulateJSON, 为什么要加这个参数呢,想知道为什么,那么就把他去掉试试,去掉了,你会发现请求失败了,报以下错误:

937897b65d46

这是个跨域请求,没有权限的问题,但是已加上这个熟悉就可以了。那我们就来看看这到底是个什么鬼。

emulateJSON

emulateJSON(布尔值)

默认值为:false,当值为true并且data为对象时,设置请求头Content-Type的值为application/x-www-form-urlencoded。

如果服务器无法处理编码为application/json的请求,可以启用emulateJSON选项。启用之后,请求会以application/x-www-form-urlencoded为MIME type,就像普通的HTML表单一样。

而this.$http.post的data默认不是以form data的形式,而是request payload, 所以需要这样设置。

当然,如果你觉得每次的请求都要加这个熟悉很麻烦的话,你也可以使用全局配置,在main.js中注册了vue-resource之后,添加以下代码即可:

Vue.http.options.emulateJSON = true;

另外还有个类似的属性emulateHTTP.

emulateHTTP

emulateHTTP(布尔值)

默认值为:false,当值为true是,用HTTP的POST方式PUT,PATCH,DELETE等请求,并设置请求头字段HTTP_Method_Override为原始请求方法。

如果Web服务器无法处理PUT, PATCH和DELETE这种REST风格的请求,你可以启用enulateHTTP现象。启用该选项后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实际的HTTP方法。

如果服务器无法处理PUT,PATCH和DELETE的请求。可以启用enulateHTTP。

启用之后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实例的HTTP方法

Vue.http.options.emulateHTTP = true;

本文为原创,转载请注明出处

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值