簡體   English   中英

錯誤:對 XMLHttpRequest 的訪問已被 CORS 策略 Flask ZDB974238714CA8DE634A7+節點JCE1D03 阻止

[英]Error: Access to XMLHttpRequest has been blocked by CORS policy Flask API + NodeJs

我在前端后端和 Flask API 之間有問題。

要執行我的項目,我會執行 `npm start. 這將在端口 3000 上運行 ReactJs 前端開發服務器。

在 package.json

我添加了以下"proxy": "http://localhost:5000",

接下來,我做

cd backend && python server.py 激活我的venv后

這將在端口 5000 上運行 Flask API

Flask API有這條路線

from flask_cors import cross_origin
# File download Link
@app.route('/filePath', methods=['POST'])
@cross_origin()
def get_path():
    data = request.get_json()["path"]
    storage.child(f"files/{data}").download(f"files/Resume.pdf")
    return "Success.."

最后,在另一個 shell 我做

cd backend && node server.js 在端口 8080 上運行

其中有以下帖子

app.post('/insert', async (req, response) => {
    const mobile_number = req.body.college_name
    const name = req.body.college_name
    axios.get('http://localhost:3000/details').then(async (res) => {
        const recruit = new RecruitModel({
            mobile_number:res.data.mobile_number, name:res.data.name,
            });
        await recruit.save()
        response.send("inserted data")
      });
});

這是前端發生錯誤的地方。

const uploadFiles = (file) => {
      //
      if (!file) return;
      if (!initialData) return null;
      const storageRef = ref(storage, `files/${file.name}`);
      const uploadTask = uploadBytesResumable(storageRef, file);
  
      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const prog = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100
          );
          setProgress(prog);
        },
        (error) => console.log(error),
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async () => {
            console.log(file.name);
            await axios.post('http://localhost:5000/filePath', {
              'path': file.name
            }).then(() => console.log(file.name));
            update();
          });
        }
      );
    };

在等待 axios.post('http://localhost:5000/filePath' 我假設。

我收到以下錯誤:

CORS 策略已阻止從源“http://localhost:3000”訪問“http://localhost:8080/insert”處的 XMLHttpRequest:“訪問控制” -Allow-Origin' header 的值 'http://localhost:5000' 不等於提供的來源

我認為使用 flask-cors 可以解決這個問題,所以我不確定為什么會出現這個錯誤。

我真的在這個錯誤上苦苦掙扎,請問有什么建議嗎?

編輯

  const addRecruit = () => {
    axios.post("http://localhost:8080/insert", {
          college_name:initialData.college_name,
          email:initialData.email, 
          mobile_number:initialData.mobile_number, name:initialData.name
    });
  }

這就是問題發生的地方。 因為數據是在 Flask 和 ReactJs 之間獲取的,但是這個 /insert 在 server.js 中

編輯說清楚了,問題與您的 Flask api 無關。 您需要在 server.js 中啟用 cors

我假設你之前有這個設置,

const cors = require('cors');
app.use(cors());

改為這樣做

const corsOptions ={
    origin:'http://localhost:3000', 
    credentials:true,            //access-control-allow-credentials:true
    optionSuccessStatus:200
}
app.use(cors(corsOptions));

不要忘記npm i cors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM