簡體   English   中英

使用 Flask RestX 啟用 Cors

[英]Enabling Cors with Flask RestX

嘗試將 CORS 添加到我的 flask 應用程序中,該應用程序使用的是使用 flask-restx 創建的 API。 希望這里有人能發現我做錯了什么。

在運行 flask 的控制台中,我沒有得到任何相關日志,並且網站說Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/api/v1/test. (Reason: CORS request did not succeed). Status code: (null). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/api/v1/test. (Reason: CORS request did not succeed). Status code: (null).

這是我的用戶案例的復制品,它給了我同樣的錯誤,並模仿了我的設置方式。

from flask import Flask
from flask_cors import CORS
from flask_restx import Namespace, Resource, Api
from flask import jsonify, make_response
from flask import Blueprint, render_template_string
import logging

logging.basicConfig()
LOGGER = logging.getLogger("reprod-case")
LOGGER.setLevel(logging.DEBUG)
LOGGER.info("Created LOGGER")
logging.getLogger('flask_cors').level = logging.DEBUG


# Create the restx namespace with a specified path
ns = Namespace(name='api_v1', path="/api/v1")


@ns.route('/test')
class Deck(Resource):
    def get(self):
        print("get")
        return make_response(jsonify({"message": "You did a Get!"}), 200)

    def put(self):
        print("Put")
        return None, 201


html_page = """
<html lang="en">
<body>
<button type="submit" name="myButton" value="Value">Click Me</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('button').on('click',function(e){
        const vote_value = e.currentTarget.attributes.value.value;
        console.log()
        $.ajax({
            type: 'GET',
            crossDomain: true,
            withCredentials: true,
            url: 'http://127.0.0.1/api/v1/test',
            contentType: 'application/json'
        })
    });
});
</script>
</body>
</html>
"""


# Blueprint for the webpage and add a route
bp = Blueprint("/", __name__)


@bp.route('/')
def home_route():
    return render_template_string(html_page)


# Setup the app, Cors, add the namespace and blueprint
def create_app():
    app = Flask(__name__)
    # CORS(app, resources={r"/api/*": {"origins": "*"}},
    CORS(app,
         resources={r"/api/*": {"origins": ['http://192.168.50.16:5000', 'http://localhost:5000']}},
         supports_credentials=True
         )

    api = Api(doc="/api/", title="Endpoints")
    api.add_namespace(ns,  path="/api/v1")
    app.register_blueprint(bp)
    api.init_app(app)
    return app


if __name__ == "__main__":
    app_ = create_app()
    app_.run(debug=True)

我還嘗試通過設置 after_request 來啟用after_request

    @app.after_request
    def enable_cors(response):
        response.headers.add("Access-Control-Allow-Headers", "authorization,content-type")
        response.headers.add("Access-Control-Allow-Methods", "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT")
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response

請參閱 RapidAPI https://rapidapi.com/guides/handle-cors-flask的這篇博文

暫無
暫無

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

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