1

I'm implementing a vegetable retail price predicting web application for one of my university projects using Flask and ReactJs. My POST requests work fine on Postman, but when I try to use a form in ReactJs to make a POST request, I get the following error:

Access to fetch at 'http://127.0.0.1:5000/vegetable' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
api_calls.js:7 POST http://127.0.0.1:5000/vegetable net::ERR_FAILED
Uncaught (in promise) TypeError: Cannot read property 'predicted_retail_price' of undefined
    at Pricing.jsx:102
TypeError: Failed to fetch api_calls.js:22
API Results:::: undefined Pricing.jsx:101 

But I have added following code segment in my server.py:

from flask import Flask, jsonify
from routes.lstm_price_route import lstm_price_blueprint
from routes.lstm_route import lstm_blueprint
from flask_cors import CORS, cross_origin
import csv
import json

server = Flask(__name__)
CORS(server)
server.config.from_object('config')

server.config['JSON_AS_ASCII'] = False
server.config['CORS_HEADERS'] = 'Content-Type'

server.register_blueprint(lstm_blueprint)
server.register_blueprint(lstm_price_blueprint)

The method in my Flask app(lstm_price_model.py):

def get_tomato_prediction(self, centre_name, date):
    Data = pd.read_csv('lstm_price_prediction_tomato.csv')
    result = {
        'predicted_retail_price': Data.loc[(Data['centre_name'] == centre_name) & (Data['date'] == date), 'predicted_retail_price'].values[0]}
    return jsonify(result)

The fetch call in React.js app(api_calls.js):

export const getPredictedPrice = async (centreName, pDate, vegetable) => {
try {
  let price_prediction = await fetch(
    `${BASE_URL}/vegetable`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        centre: centreName,
        date: pDate,
        commodity: vegetable
      })
    }
  );
  let result = await price_prediction.json();
  return result;
 } catch (error) {
  console.log(error);
 }
};

Github link for the frontend code - https://github.com/HashiniW/CDAP-F

Github link for the backend code - https://github.com/HashiniW/CDAP-B

Any suggestions to overcome this error? Thank You!

Hashini
  • 89
  • 1
  • 11

2 Answers2

0

Try using mode: "no-cors" on the fetch frontend.

export const getPredictedPrice = async (centreName, pDate, vegetable) => {
  try {
    let price_prediction = await fetch(
      `${BASE_URL}/vegetable`,
      {
        //Adding mode: no-cors may work
        mode: "no-cors",

        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          centre: centreName,
          date: pDate,
          commodity: vegetable
        })
      }
    );
    let result = await price_prediction.json();
    return result;
  } catch (error) {
    console.log(error);
  }
};
Dom Webber
  • 21
  • 4
  • 2
    Maybe try looking at [flask-cors](https://flask-cors.readthedocs.io/en/latest/) or [this answer and thread](https://stackoverflow.com/a/26395623/11928183) – Dom Webber Jan 09 '21 at 16:36
0

Use following code in your python project :


from flask import Flask, jsonify
from routes.lstm_price_route import lstm_price_blueprint
from routes.lstm_route import lstm_blueprint
from flask_cors import CORS, cross_origin
import csv
import json

server = Flask(__name__)
cors = CORS(server , resources={r"/*": {"origins": "*", "allow_headers": "*", "expose_headers": "*"}})

server.register_blueprint(lstm_blueprint)
server.register_blueprint(lstm_price_blueprint)

Soroosh Khodami
  • 1,185
  • 9
  • 17
  • 1
    Actually the error was in the way which I didn't handle the null values in the predictions I'm retrieving to the frontend. I haven't added a proper error handling in my backend so that was the reason. Thank for your suggestion btw :) – Hashini Jan 18 '21 at 14:51