Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 860
Pwinchester Avatar asked Dec 24 '22 23:12

Pwinchester


1 Answers

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)
like image 150
Mike Tung Avatar answered Dec 28 '22 08:12

Mike Tung