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!