get请求可以传body吗_21. Vue 使用 vueresource 发起get、post、jsonp请求的基本用法

前言

最近忙得冒烟,趁有时间赶紧补上Vue系列篇章。

介绍

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

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

下载 vue-resource

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

32256bdfdc1bdb4a6e1d1a350f2570da.png

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

c6fe407b3721d0ef7a5456a52f924be3.png

导入 vue-resource


<script src="lib/vue.js">script>

<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请求
60860d54a08b5873239171d67a50ba74.png
  • 执行post请求
f985fd0f727de5a3c43e2b1b7dcb1572.png

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

span style="line-height: 26px;">html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>

<script src="/static/vue.js">script>

<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请求
8835258f165a76b66245b4a53b563382.png
  • 执行POST请求
ca7f29af821e779a3f809ab09fde67aa.png
  • 执行JSONP请求
05b224b96331a07c9f03839dca2ac4d5.png

交流QQ群:

6f27333daafcb15805ab25495c2d177b.png

05153283d2d96b913beca7f6da2f2e2a.gif

点击下面,查看更多Vue系列文章

b7325323efbe6d97fe4ee5c551be2521.pngb7b2da0ff3be5e274d5ee86b0990edd1.gif

a2c6fc24c773f691a8041d148f14ba74.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值