Javascript获取Flask JSON [英] Javascript fetch flask json

查看:105
本文介绍了Javascript获取Flask JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将Flask服务器连接到前端create react应用程序.现在,我只想验证我是否可以在两者之间发送json.下面是每个代码以及有关错误的更多描述.

So I'm trying to connect a Flask server to a front end create react app. Right now I just want to verify that I can send json between the two. Below is the code for each and a bit more description on the errors.

创建React App提取

Create React App fetch

import React, { Component } from 'react';
import './App.css';

export default class App extends Component {
  constructor() {
    super()

    this.state = {
      pyResp: []
    }
  }

 fetchHelloWorld() {
    console.log("fetching python localhost");
    fetch('http://localhost:5000/', {
      method: 'GET',
      mode:'no-cors',
      dataType: 'json'
    })
      .then(r => r.json())
      .then(r => {
        console.log(r)
        this.setState({
          pyResp: r
        })
      })
      .catch(err => console.log(err))
  }

  render() {
    return (
      <div className="App">
        <h1>Blockchain Voter</h1>
        <p>
          {this.state.pyResp}
        </p>
        <button onClick={() => this.fetchHelloWorld()}>Python</button>
      </div>
    );
  }
}

烧瓶服务器

from flask import *
from json import *

app = Flask(__name__)

@app.route('/')
def hello_world():
    jsonResp = {'jack': 4098, 'sape': 4139}
    print(jsonify(jsonResp))
    return jsonify(jsonResp)

if __name__ == '__main__':
    app.run(debug=True)

我收到此错误(在chrome控制台中)-

I get this error (in the chrome console) -

输入意外结束(…)

Unexpected end of input(…)

我可以在Chrome的网络"标签中看到json,它似乎在解析时出错.

I can see the json in the Networks tab in Chrome, it just seems to be erroring on the parsing.

坚持认为这是烧瓶语法错误(即未正确发送),JavaScript解析错误(即我犯了一些我看不到的简单错误)还是我没有创建的React应用程序错误不明白.

Stuck on whether this is a flask syntax error (i.e. not sending it correctly), a javascript parsing error (i.e. I'm making some simple mistake I can't see), or a create react app bug that I don't understand.

推荐答案

您很可能没有在Flask应用程序中启用CORS. CORS代表跨源资源共享(Cross Origin Resource Sharing),它允许python网络应用说出与我们共享或与浏览器共享的内容.无论如何,解决方案应该是这样的.

You most likely do not have CORS enabled in your Flask application. CORS stands for Cross Origin Resource Sharing which allows python webapps to say OK we share with or browser or whatever. Anyway the solution should be something like this.

在终端/重击中$ pip install -U flask-cors

在您的应用中

from flask import *
from json import *
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route('/')
def hello_world():
    jsonResp = {'jack': 4098, 'sape': 4139}
    print(jsonify(jsonResp))
    return jsonify(jsonResp)

if __name__ == '__main__':
    app.run(debug=True)

这篇关于Javascript获取Flask JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆