Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - No 'Access-Control-Allow-Origin' header is present on the requested resource (FLASK API / ReactJs)

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!

question from:https://stackoverflow.com/questions/65644658/no-access-control-allow-origin-header-is-present-on-the-requested-resource-fl

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

1 Reply

0 votes
by (71.8m points)

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);
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...