学习如何接收uni-app的请求并将数据返回给uni-app显示出来
例如:一个项目需要查数据库,大家知道前端操作不安全,所以我们需要把请求发送给python后端,python后端在处理数据并把数据发送给前端
由于flask不是python的标准库,所以需要安装
pip install flask
easy_install flask
因为存在跨域问题,需要使用flask_cors来修饰
pip install flask-cors
只需要建一个.py文件即可,不用新建flask项目
如果已经下载了flask和flask_cors,那么即开始写代码
# -*- coding: utf-8 -*-
# antuor:dxiaod
from flask import Flask, request
from flask_cors import *
app = Flask(__name__)
注意:一定要加上@cross_origin(),否则会出现跨域问题
@app.route('/request',methods=['GET'])
@cross_origin()#加上cros修饰,否则会出现跨域问题
def get_text_input():
text = request.args.get('inputstr')
print(text)
return "成功接收消息:"+text #给uni-app传回数据
app.run(host='127.0.0.1', port=8080 ,debug=True)
# -*- coding: utf-8 -*-
# antuor:dxiaod
from flask import Flask, request
from flask_cors import *
app = Flask(__name__)
@app.route('/request',methods=['GET'])
@cross_origin()
def get_text_input():
text = request.args.get('inputstr')
print(text)
return "成功接收消息:"+text
app.run(host='127.0.0.1', port=8080 ,debug=True)
uni.request({
})
注意:此处的url必须要和flask的url相同
url: 'http://127.0.0.1:8080/request',
注意:data中inputstr就是request.args.get(‘inputstr’)
data: {
inputstr: '已跳转到首页'
},
header: {
'custom-type': 'application/json'
},
success: (res) => {
console.log(res.data);
}
uni.request({
url: 'http://127.0.0.1:8080/request',
data: {
inputstr: '已跳转到首页'
},
header: {
'custom-type': 'application/json'
},
success: (res) => {
console.log(res.data);
}
})
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 207-656-920
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
09:54:40.366 请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。
09:54:40.366 正在编译中...
09:54:42.527 INFO Starting development server...
当你已经点击指定按钮调用uni.request函数时,回头再来看python的运行结果
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 207-656-920
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [19/Aug/2020 09:54:57] "OPTIONS /request?inputstr=已跳转到首页 HTTP/1.1" 200 -
127.0.0.1 - - [19/Aug/2020 09:54:57] "GET /request?inputstr=已跳转到首页 HTTP/1.1" 200 -
已跳转到首页
然后打开前端浏览器开发者工具
[HMR] Waiting for update signal from WDS...
DevTools failed to load SourceMap: Could not load content for http://localhost:8081/static/js/sockjs.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
App.vue:4 App Launch
App.vue:7 App Show
chunk-vendors.js:11780 Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
app.vue:44 unknown
app.vue:53 检测到了网络
app.vue:39 成功接收消息:已跳转到首页
有一个成功接收消息:已跳转到首页
,这就是flask的return "成功接收消息:"+text
已经成功接收消息了