javascript 即使在后端设置了CORS,CORS也阻止了对XMLHttpRequest的访问

gblwokeq  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(177)

我有一个 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)
    })
}
x7rlezfr

x7rlezfr1#

您需要在Access-Control-Allow-Headers中指定Origin
因此axios请求应该类似于...

axios({
    method: 'post',
    headers: {
        'Access-Control-Allow-Headers': ['Origin'],
        'Access-Control-Allow-Origin': 'http://127.0.0.1:5000/predict',
    }
    ...
})

来自文档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.

相关问题