VUE请求数据的常用方式有三种:
vue-resource
axios
fetch-jsonp
今天我们先来说一下vue-resource
一、优势及特点:
1. 体积小 vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
2. 支持主流的浏览器 和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。
3. 支持Promise API和URI Templates Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。 URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。
4. 支持拦截器 拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。
5.支持跨域。axios不支持。
二、用法
首先可以参考在github上搜索vue-resource,有详细的用法说明:https://github.com/pagekit/vue-resource
1、安装vue-resource模块 注:命令需加上 --save
npm install vue-resource --save / cnpm install vue-resource --save
2、main.js 引入 vue-resource
import VueResource from 'vue-resource'
Vue.use(VueSource)
3、在组件中直接使用
// 基于全局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);
4、参数说明:
vue-resource支持的restful风格七种请求方式:
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
option的参数说明:
参数 | 类型 | 描述 |
---|---|---|
url | string | 请求的目标URL |
body | Object , FormData , string | 作为请求体发送的数据 |
headers | Object | 作为请求头部发送的头部对象 |
params | Object | 作为URL参数的参数对象 |
method | string | HTTP方法 (例如GET,POST,...) |
timeout | number | 请求超时(单位:毫秒) (0 表示永不超时) |
before | function(request) | 在请求发送之前修改请求的回调函数 |
progress | function(event) | 用于处理上传进度的回调函数 ProgressEvent |
credentials | boolean | 是否需要出示用于跨站点请求的凭据 |
emulateHTTP | boolean | 是否需要通过设置X-HTTP-Method-Override 头部并且以传统POST方式发送PUT,PATCH和DELETE请求。 |
emulateJSON | boolean | 设置请求体的类型为application/x-www-form-urlencoded |
三、搭建前后端服务用于发送,解析,展示请求的整个流程
1、后端项目服务搭建。
创建一个maven项目。
pom文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ampthon</groupId>
<artifactId>springboot_test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.53</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
启动类代码:
package com.ampthon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
System.out.println("项目开始启动");
SpringApplication.run(MySpringBootApplication.class);
System.out.println("项目启动完成");
}
}
controller代码:
package com.ampthon.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
public class QuickStartController
{
@CrossOrigin //解决跨域问题
@GetMapping("/getData")
public List<String> getData(HttpServletRequest request, HttpServletResponse response){
System.out.println("getData invoke start");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(!"stalin".equals(username)||!"123".equals(password)){
return null;
}
List<String> list = new ArrayList<>();
list.add("讲个笑话:美股大跌,中国跟不跟?");
list.add("A股坚决反对美股不符合实际国情的涨势。");
list.add("涨我们坚决不跟,跌我们奉陪到底!");
return list;
}
@CrossOrigin //解决跨域问题
@PostMapping("/postData")
public List<String> postData(@RequestBody JSONObject jsonParam,HttpServletResponse response){
System.out.println("postData invoke start");
Map<String,String> params = (Map)jsonParam.get("params");
String username = params.get("username");
String password = params.get("password");
if(!"stalin".equals(username)||!"123".equals(password)){
return null;
}
List<String> list = new ArrayList<>();
list.add("今天又是吃面的一天");
list.add("说好的独立行情呢~");
list.add("不过长期看好中国的半导体发展,打铁还得自身硬");
return list;
}
}
2.前端项目服务搭建。
main.js文件:
import Vue from 'vue';
import App from './App.vue';
import VueResource from 'vue-resource';
Vue.use(VueResource)
new Vue({
el: '#app',
render: h => h(App)
})
App.vue文件
<template>
<div id="app">
<hr>
<br>
<button @click="getData()">获取get请求数据</button>
<br>
<ul>
<li v-for="item in getList">
{{item}}
</li>
</ul>
<br>
<hr>
<br>
<button @click="getDataByPost()">获取post请求数据</button>
<ul>
<li v-for="item in postList">
{{item}}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
getList:[],
postList:[]
}
},
methods: {
getData(){
//请求数据(获取一个网站的内容标题并展示)
// var api = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"
// this.$http.get(api).then((response)=>{ //get请求
// console.log(response);
// //注意list指向
// this.list=response.body.result;
// }
// ,function(err){
// console.log(err);
// })
//get请求
var getApi = "http://127.0.0.1:8080/getData?username=stalin&password=123"
this.$http.get(getApi).then((response)=>{
console.log(response);
this.getList = response.body;
})
},
getDataByPost(){
var postApi = "http://127.0.0.1:8080/postData"
//post请求
this.$http.post(postApi,{params:{"username":"stalin","password":"123"}}).then(function(res){
console.log(res);
console.log(res.body);
this.postList=res.body;
});
}
},
mounted() {
// this.getData();
}
}
</script>
<style lang="scss">
</style>
四、启动服务,看结果~
注:由于未配置前后端的端口号,所以需要先启动后端程序,再启动前端程序。
请求数据流程: 访问前端程序->点击请求按钮->请求后端接口->后端收到请求报文处理后返回响应报文->前端对后端返回的响应报文进行解析和展示。
最终结果如下:
1.打开前端页面:
2.点击按钮发起请求:
喜欢的朋友欢迎点赞,评论,关注哦~~