开发者问题收集

请求的资源上不存在“Access-Control-Allow-Origin”标头(FLASK API / ReactJs)

2021-01-09
2097

我正在使用 Flask 和 ReactJs 为我的一个大学项目实现一个蔬菜零售价格预测网络应用程序。我的 POST 请求在 Postman 上运行良好,但是当我尝试使用 ReactJs 中的表单发出 POST 请求时,出现以下错误:

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 

但是我在 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)

我的 Flask 应用程序(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)

React.js 应用程序(api_calls.js)中的 fetch 调用:

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 链接 - https://github.com/HashiniW/CDAP-F

后端代码的 Github 链接 - https://github.com/HashiniW/CDAP-B

有什么建议可以解决此错误?谢谢!

2个回答

尝试在获取前端使用 mode: "no-cors"

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
2021-01-09

在您的 Python 项目中使用以下代码:


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
2021-01-18