Uni-app+Flask前后端传参
来自CloudWiki
背景
学习如何接收uni-app的请求并将数据返回给uni-app显示出来
例如:一个项目需要查数据库,大家知道前端操作不安全,所以我们需要把请求发送给python后端,python后端在处理数据并把数据发送给前端
环境准备(后端)
安装Flask
pip install flask
因为存在跨域问题,需要使用flask_cors来修饰
pip install flask-cors
Flask代码
test.py:
# -*- 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=5000)
python test.py 运行这段代码 (或云服务器环境下后台运行:nohup python3 -u test.py > test.log 2>&1 &)
在浏览器输入http://127.0.0.1:5000/request?inputstr=123#/
如果正常,会显示如下页面:
Uni-app代码
<template> <view> <view class="demo" @click="setInfo">查询</view> <view>{{info}}</view> </view> </template> <script> export default { data() { return { info: '暂无' } }, methods: { setInfo() { uni.request({ url: 'http://127.0.0.1:5000/request', data: { inputstr: '已跳转到首页' }, header: { 'custom-type': 'application/json' }, success: (res) => { console.log(res.data); this.info =res.data } }) }, } } </script> <style> .demo { width: 100px; margin: 50px auto; background: #8F8F90; height: 100px; } </style>
一点击中间按钮,‘暂无’的文字会被替换成从后台传来的数据。
参考文档
参考文档:https://blog.csdn.net/weixin_47597012/article/details/108092533