Hardware and software Environment

  • windows 10 64bit
  • Anaconda3 with python 3.7
  • Pycharm 2020.1.2
  • Flask 1.1.2
  • Flask – restful 0.3.8
  • Flask – cors 3.0.8

Cross domain access

What is cross-domain?

Cross-domain means that the browser is from the serverAStatic resources obtained, includinghtml,css,javascriptAnd then injavascriptThrough theajaxAccess serverBStatic resource or request.

CORS

The W3C has developed a specification for Cross Origin Resource Sharing, or CORS, which is now supported by most browsers.

Use the example from the previous article

from flask import Flask, jsonify
from flask_restful import Api, Resource, reqparse


USERS = [
    {"name": "zhangsan"},
    {"name": "lisi"},
    {"name": "wangwu"},
    {"name": "zhaoliu"}]class Users(Resource) :
    def get(self) :
        return jsonify(USERS)

    def post(self) :
        args = reqparse.RequestParser() \
            .add_argument('name'.type=str, location='json', required=True.help="Name cannot be empty.") \
            .parse_args()

        self.logger.debug(args)

        if args['name'] not in USERS:
            USERS.append({"name": args['name']})

        return jsonify(USERS)


app = Flask(__name__)
api = Api(app, default_mediatype="application/json")

api.add_resource(Users, '/users')

app.run(host='0.0.0.0', port=5001, use_reloader=True, debug=True)
Copy the code

Front-end page index.html

<html>
<body>

<button type="button" onclick="jump()">Click Me!</button>
<script>
    function jump(){
        let xhr = new XMLHttpRequest();
        xhr.open('GET'."http://192.168.1.210:5001/users".true);
        xhr.send();

        xhr.onreadystatechange = processRequest;

        function processRequest(e) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let response = JSON.parse(xhr.responseText);
                console.log(response)
            }
        }
    }
</script>
</body>
</html>
Copy the code

We deploy index.html on one machine (192.168.1.140), flask application on another machine (192.168.1.210), then access index.html in a browser, click the button in the page, and an error is reported

Flask configuration cors

CORS needs to be configured in the backend application. In Flask, you can use the extension Flask-CORS, installed first

pip install flask-cors
Copy the code

Then go to manage.py, import the module, and include the Flask application as follows

from flask_cors import CORS

app = Flask(__name__)
CORS(app)
Copy the code

Restart the application, access index.html again, and the result should be normal