首页 > 解决方案 > 如何将 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”,我只想发送数据以做出反应

标签: reactjsmongodbflaskpymongo

解决方案


所以我想通了,我希望将来遇到这个问题的任何人都能看到这一点。

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 在反应


推荐阅读