0
点赞
收藏
分享

微信扫一扫

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法

介绍

Vue 可以使用 vue-resource 发起get、post、jsonp请求,还可以使用 ​​axios​​的第三方包实现实现数据的请求。

本章节来介绍如何使用​​vue-resource​​​,使用​​flask​​框架编写后端业务处理get、post、jsonp请求。

下载 vue-resource

vue-resource的Github:​​https://github.com/pagekit/vue-resource​​


25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_vue.js


访问 ​​https://cdn.jsdelivr.net/npm/vue-resource@1.5.1​​,然后右键保存该js文件即可。


25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_json_02


导入 vue-resource

<!--  1.导入vue.js库  -->
<script src="lib/vue.js"></script>
<!-- 2.导入vue-resource,注意:需要先引入vue.js -->
<script src="lib/vue-resource@1.5.1"></script>

1.示例:实现最简单的get、post请求

1.1 使用flask框架,编写get、post处理业务

from flask import Flask, jsonify,request,render_template

# 实例化app
app = Flask(import_name=__name__)

@app.route('/vue_test', methods=["GET"])
def vue_test():

return render_template('vue_test.html')


@app.route('/login', methods=["GET","POST"])
def login():

method = request.method

return jsonify(token=123456, gender=0, method = method)


if __name__ == '__main__':
app.run(debug=True)

使用postman调试如下:

  • 执行get请求

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_vue.js_03


  • 执行post请求

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_flask_04


1.2 使用 vue-resource 发起 get、post请求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 1.导入vue.js库 -->
<script src="/static/vue.js"></script>
<!-- 2.导入vue-resource,注意:需要先引入vue.js -->
<script src="/static/vue-resource-1.5.1.js"></script>

</head>
<body>

<div id="app">
<input type="button" value="get请求" @click="getInfo">
<input type="button" value="post请求" @click="postInfo">
<input type="button" value="jsonp请求" @click="jsonpInfo">
</div>

<script>

// 2. 创建一个Vue的实例
var vm = new Vue({
el: '#app',
data: {},
methods: {
getInfo() { // 发起get请求
// 当发起get请求之后, 通过 .then 来设置成功的回调函数
this.$http.get('/login').then(function (result) {
// 通过 result.body 拿到服务器返回的成功的数据
// console.log(result.body)
})
},
postInfo() { // 发起 post 请求 application/x-wwww-form-urlencoded
// 手动发起的 Post 请求,默认没有表单格式,所以,有的服务器处理不了
// 通过 post 方法的第三个参数, { emulateJSON: true } 设置 提交的内容类型 为 普通表单数据格式
this.$http.post('/login', {}, { emulateJSON: true }).then(result => {
console.log(result.body)
})
},
jsonpInfo() { // 发起JSONP 请求
// this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => {
this.$http.jsonp('http://127.0.0.1:5000/login').then(result => {
console.log(result.body)
})
}
},

});


</script>

</body>
</html>

启动Flask服务,测试三个请求如下:

  • 执行GET请求

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_flask_05


  • 执行POST请求

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_json_06


  • 执行JSONP请求

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_json_07

25. Vue 使用 vue-resource 发起get、post、jsonp请求的基本用法_json_08


举报

相关推荐

0 条评论