react-解決 fetch 跨域問題:Access to fetch at XXX from origin YYY has been blocked by CORS policy

四四17發表於2020-11-03

參考連結(對我沒用):
https://blog.csdn.net/qq_41956139/article/details/106564357

https://blog.csdn.net/weixin_44415625/article/details/87607924?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

  1. 在post請求裡新增請求體:

    static post(url, data){
        return new Promise((resolve, reject) =>{
            fetch(url,{
                method:'POST',
                headers:{
                    'Accept':'application/json',
                    'Content-Type':'application/json',
                    'Access-Control-Allow-Origin':'*',
                    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
                    'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
                },
                body:JSON.stringify(data)
            })
                .then(response=>response.json())
                .then(result=>resolve(result))
        })
    }
    
  2. 在response的py檔案中新增請求頭部

    @app.route('/data', methods=['POST'])
    def getInfo():
        response = Response("data")
        response.headers.set('Access-Control-Allow-Origin', '*')
        response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
        data = request.get_data(as_text=True)
        re = {
        'code': 0,
        'data':data,
        'message': "這是測試呀"
        }
        print("後端資料:", data)
        return json.dumps(re)
    

上面的都沒啥用!!!

有用的解決辦法:

import flask
from flask import Flask, request, jsonify, Response, make_response
import json
from flask_cors import *

app = Flask(__name__, template_folder='../frontend', static_folder='../frontend', static_url_path='')

#看這裡!
CORS(app, supports_credentials=True)

相關文章