Search code examples
javascriptpythonjsonflaskcreate-react-app

Javascript fetch flask 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.

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.


Solution

  • 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)