Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

javascript - Uncaught (in promise) TypeError: Failed to fetch - Flask + React

I am building a very simple machine learning app using a flask backend and a react frontend.

I found inspiration for the project here.

https://towardsdatascience.com/create-a-complete-machine-learning-web-application-using-react-and-flask-859340bddb33

However when I run the servers, I get the following error in the console.

Uncaught (in promise) TypeError: Failed to fetch
@   App.js:51
.then(response => {

That's the line in my code that is calling the error. I tried changing the http protocol to https, as well as playing around with some of the headers (to no avail). I'm thinking this perhaps may be a CORS issue? Any help would be immensely appreciated.

Here's my relevant code:

App.js

import React, { Component } from 'react';
import './App.css';
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Button from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.css';

class App extends Component {

 constructor(props) {
  super(props);

  this.state = {
   isLoading: false,
   formData: {
    happy: 0,
    stress: 0,
    eyes: 0
  },
  result: ""
 };
}

handleChange = (event) => {
 const value = event.target.value;
 const name = event.target.name;
 var formData = this.state.formData;
 formData[name] = value;
 this.setState({
  formData
 });
}

handlePredictClick = (event) => {
 const formData = this.state.formData;
  console.log('formData', formData);
 this.setState({ isLoading: true });
 fetch('http://127.0.0.1:5000/prediction/', 
  {
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    method: 'POST',
    body: JSON.stringify(formData)
  })
  .then(response => response.json())
  // console.log('response', response)
  .then(response => {
    this.setState({
      result: response.result,
      isLoading: false
    });
  });
 }

handleCancelClick = (event) => {
 this.setState({ result: "" });
}

render() {
 const isLoading = this.state.isLoading;
 const formData = this.state.formData;
 const result = this.state.result;

 var happys = []
 for (var i = 0; i <= 100; i = +(i + 1).toFixed(1)) {
  happys.push(<option key = {i} value = {i}>{i}</option>);
 }
 var stresses = []
 for (var i = 0; i <= 100; i = +(i + 1).toFixed(1)) {
  stresses.push(<option key = {i} value = {i}>{i}</option>);
 }
 var eyesss = []
 for (var i = 0; i <= 100; i = +(i + 1).toFixed(1)){
  eyesss.push(<option key = {i} value = {i}>{i}</option>);
 }


return (
  <Container>
    <div>
      <h1 className="title">Plant Classifier</h1>
    </div>
    <div className="content">
      <Form>
        <Form.Row>
          <Form.Group as={Col}>
            <Form.Label>Happy</Form.Label>
            <Form.Control 
              as="select"
              value={formData.happy}
              name="happy"
              onChange={this.handleChange}>
              {happys}
            </Form.Control>
          </Form.Group>
          <Form.Group as={Col}>
            <Form.Label>Stress</Form.Label>
            <Form.Control 
              as="select"
              value={formData.stress}
              name="stress"
              onChange={this.handleChange}>
              {stresses}
            </Form.Control>
          </Form.Group>
        </Form.Row>
        <Form.Row>
          <Form.Group as={Col}>
            <Form.Label>Eyes</Form.Label>
            <Form.Control 
              as="select"
              value={formData.eyes}
              name="eyes"
              onChange={this.handleChange}>
              {eyesss}
            </Form.Control>
          </Form.Group>
        </Form.Row>
        <Row>
          <Col>
            <Button
              block
              variant="success"
              disabled={isLoading}
              onClick={!isLoading ? this.handlePredictClick : null}>
              { isLoading ? 'Making prediction' : 'Predict' }
            </Button>
          </Col>
          <Col>
            <Button
              block
              variant="danger"
              disabled={isLoading}
              onClick={this.handleCancelClick}>
              Reset prediction
            </Button>
          </Col>
        </Row>
      </Form>
      {result === "" ? null :
        (<Row>
          <Col className="result-container">
            <h5 id="result">{result}</h5>
          </Col>
        </Row>)
      }
    </div>
  </Container>
);
}
}

export default App;

App.py

from flask import Flask, request, jsonify, make_response
from flask_restplus import Api, Resource, fields
from sklearn.externals import joblib
import numpy as np
import sys

flask_app = Flask(__name__)
app = Api(app = flask_app, 
      version = "1.0", 
      title = "Iris Plant identifier", 
      description = "Predict the type of iris plant")

name_space = app.namespace('prediction', description='Prediction APIs')

model = app.model('Prediction params', 
              {'happy': fields.Integer(required = True, 
                                           description="happy", 
                                           help="happy cannot be blank"),
              'stress': fields.Integer(required = True, 
                                           description="stress", 
                                           help="stress cannot be blank"),
              'eyes': fields.Integer(required = True, 
                                        description="eyes", 
                                        help="eyes cannot be blank")})

classifier = joblib.load('classifier.joblib')

@name_space.route("/")
class MainClass(Resource):

 def options(self):
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add('Access-Control-Allow-Headers', "*")
    response.headers.add('Access-Control-Allow-Methods', "*")
    return response

 @app.expect(model)     
 def post(self):
    try: 
        formData = request.json
        data = [val for val in formData.values()]
        prediction = classifier.predict(np.array(data).reshape(1, -1))
        types = { 0: "Hybrid", 1: "Indica", 2: "Sativa"}
        response = jsonify({
            "statusCode": 200,
            "status": "Prediction made",
            "result": "The type of pot plant is: " + types[prediction[0]]
            })
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    except Exception as error:
        return jsonify({
            "statusCode": 500,
            "status": "Could not make prediction",
            "error": str(error)
        })

Here is a snapshot of my data:

index.  |.  name. |.   rating. |.   phenotype.  |.     Happy.  |.    Stress.  |.   Eyes
  0         john.        7.           Hybrid             76             34           5
  1.        sally        3            Indica                            33           78.         
  2         joey         55           Sativa.             23                         55
question from:https://stackoverflow.com/questions/65851575/uncaught-in-promise-typeerror-failed-to-fetch-flask-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...