reactjs - 如何将 mongodb json 带到烧瓶中做出反应?
问题描述
所以我想拿我的 mongo db 并在反应中使用它,它很小,所以它不会压倒反应。我的烧瓶看起来像这样
import subprocess
from flask import Flask, request, jsonify, json
from flask_cors import CORS, cross_origin
import pymongo
disaster = ""
app = Flask(__name__)
CORS(app, support_credentials=True)
client = pymongo.MongoClient("NOT IMPORTANT FOR GITHUB")
db = client["twitterdb"]
col = db["tweets"]
our_mongo_database_compressed = col.find({},{'user.created_at':1, 'user.location':1,'_id':0})
def request_tweets(disaster):
print(disaster)
#subprocess.call("./../../../backend/get_tweets", disaster)
@app.route('/refresh_data', methods=['GET', 'POST'])
#@cross_origin(supports_credentials=True)
def refresh_data():
disaster = request.get_json()
request_tweets(disaster)
x = 0
y = []
for datas in our_mongo_database_compressed:
y.append(datas)
if(x > 100):
break
x+=1
#print(y)
return str(y)
我的反应功能看起来像
this.setState({
disaster: event.target.value
})
axios.post('http://localhost:5000/refresh_data', [this.state.disaster])
.then(function(response){
console.log(JSON.parse(response.data));
})
}
我在位置 2 的 JSON 中不断收到“Unexpected token”,我只想发送数据以做出反应
解决方案
所以我想通了,我希望将来遇到这个问题的任何人都能看到这一点。
for datas in our_mongo_database_compressed:
y.append(datas)
这将创建一个字典数组。所以 y[0]["user"]["location"] 将是您从该数组中获取元素的方式。
考虑到这一点,我们需要将此数组更改为 JSON 字符串,这是一种用于在烧瓶和反应之间传输的数据类型,以便您返回
return json.dumps(y)
现在你可能会认为这意味着你在写的时候在 React 中得到了一个字符串
JSON.parse(response.data)
不。那太容易了,你有一个秘密的字符串响应对象。因此,您需要使用 JSON stringify 将响应对象更改为字符串
JSON.parse(JSON.stringify(response.data))
现在你有你的 json 在反应
推荐阅读
- selenium - 我们可以将 Robot 框架与黄瓜框架 java 一起使用吗?
- python - 如何在时间序列和绘图中找到增量值?
- django - 如何在石墨烯中将函数作为查询结果返回?
- node.js - PassThrough stream.write 何时抛出 ERR_STREAM_DESTROYED 或在销毁后不执行任何操作?
- php - 如何使用 Firebase 向 5000 多个用户发送通知?
- ios - 无法在 repo 中推送 github 克隆的 Xcode 项目
- java - 我的 FlinkKafkaProducer011 需要的参数比预期的要少
- powershell - Powershell Arraylist RemoveAt 不工作
- java - 如何获取子类对象的引用类
- python - AES解密——java到python代码转换