Javascript fetch flask json

馋奶兔 提交于 2021-02-07 09:11:24

问题


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.

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>
    );
  }
}

Flask Server

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)

I get this error (in the chrome console) -

Unexpected end of input(…)

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

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.


回答1:


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.

In the terminal/bash $ pip install -U flask-cors

In your app

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)


来源:https://stackoverflow.com/questions/40915319/javascript-fetch-flask-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!