我有一个 flask 后端和一个React前端。我试图做一个POST请求到我的后端,但得到错误:
Access to XMLHttpRequest at 'http://127.0.0.1:5000/predict' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
下面是我的 flask 代码:
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
cors = CORS(app, resource={
r"/*":{
"origins": "*"
}
})
@app.route('/predict', methods=['GET','POST'])
def home():
df = pd.DataFrame(request.json["challenge"])
...
return pd.DataFrame.to_json(result)
app.run(port=5000)
这是我从前端发出的axios请求:
function getPrediction(data) {
const sending = {}
sending['challenge'] = fighters
axios.post('http://127.0.0.1:5000/predict', sending, {
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then((res) => {
console.log(res)
})
}
1条答案
按热度按时间x7rlezfr1#
您需要在
Access-Control-Allow-Headers
中指定Origin
因此axios请求应该类似于...
来自文档https://flask-cors.readthedocs.io/en/latest/configuration.html#configuration-options
允许标头:
Headers to accept from the client. Headers in the Access-Control-Request-Headers request header (usually part of the preflight OPTIONS request) matching headers in this list will be included in the Access-Control-Allow-Headers response header.
允许原点:
The origin(s) to allow requests from. An origin configured here that matches the value of the Origin header in a preflight OPTIONS request is returned as the value of the Access-Control-Allow-Origin response header.