Vue基于vue-resource的post和get请求
Posted 码农小黑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue基于vue-resource的post和get请求相关的知识,希望对你有一定的参考价值。
首先需要安装vue-resource
npm install vue-resource --save
然后在main.js中引入并使用
import VueResource from 'vue-resource'
Vue.use(VueResource)
1、post请求示例(Request Payload)
register(){
this.$http.post('http://localhost:8088/user/register',
{
username:'admin',
password:'admin'
}
).then(function(res){
console.log("响应结果res")
console.log(res)
});
}
默认发送的数据是request payload格式的,即json格式;还有一种是formData格式的,相当于key=11&value=12这种形式
对于 Request Payload 请求, 后台必须使用 @RequestBody注解通过实体Bean来接收传输的json对象
对于 Form Data 请求,无需任何注解,可使用实体Bean直接接收,也能通过request.getParameter("uasername")形式来获取uasername对应的值
1.1 前台请求
在浏览器通过F12打开开发者工具,可以看到请求头中的Content-Type为json格式
发送的数据格式是Request Payload
1.2 后台
后台接收请求后只能通过@RequestBody注解来接收数据,通过request.getParameter方法无法获取数据,如下图

1.3 响应结果
响应结果封装在了res中,可通过res.body获取响应体

2、post请求示例(Form Data)
如果想发送Form Data 请求,可设置 emulateJSON: true,将请求修改如下:
register(){
this.$http.post('http://localhost:8088/user/register',
{
username:'admin',
password:'admin'
},
{
emulateJSON: true
}
).then(function(res){
console.log("响应结果res")
console.log(res.body)
});
}
2.1 前台请求
在浏览器通过F12打开开发者工具,可以看到请求头中的Content-Type为application/x-www-form-urlencoded格式
发送的数据格式是Form Data

2.2 后台
后台不需要通过@RequestBody注解来接收数据,普通实体类接收即可,通过request.getParameter也能获取数据,如下图

2.3 响应结果
响应结果封装在了res中,可通过res.body获取响应体

3、get请求示例
register(){
this.$http.get('http://localhost:8088/user/register',
{
params: {
username:'admin',
password:'password'
}
}
).then(function(res){
console.log("响应结果res")
console.log(res)
});
}
get请求数据都是Query String Parameters
以上是关于Vue基于vue-resource的post和get请求的主要内容,如果未能解决你的问题,请参考以下文章