问题描述
我正在使用 Flask 和 ReactJs 为我的一个大学项目实施蔬菜零售价格预测 Web 应用程序。我的 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
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 app(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
有什么建议可以克服这个错误?谢谢!
解决方法
尝试在获取前端使用 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);
}
};
,
在你的 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)