Hello World App Demonstrating CORS using Flask


Here we will demostrate Cross-Orgin Resourse Sharing using Flask:

1) First, we will write the server code in file "HelloWorldServer.py":

from flask_cors import CORS, cross_origin
from flask import Flask
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# POST
@app.route("/helloworld", methods = ['POST'])
@cross_origin()
def helloWorld():
    return "Hello World!"
# GET
@app.route("/")
@cross_origin() # allow all origins all methods.
def hello():
    return "Hello, cross-origin-world!"
if __name__ == "__main__":
    app.run(host = "0.0.0.0", port = 5050)

2.A.) Client code using Python in file "HelloWorldClient.py":

import requests
headers = {'content-type': 'application/json'}

URL = "http://127.0.0.1:5050/helloworld"
r = requests.post(url = URL, data = {}, headers = headers)
print("Response text: " + r.text)

URL = "http://127.0.0.1:5050"
r = requests.get(url = URL, data = {}, headers = headers)
print("Response text: " + r.text)


2.B.) Client code using JavaScript in file "HelloWorldClient.html":

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: 'http://127.0.0.1:5050/helloworld',
            method: 'POST',
            data: {},
            dataType: "text" /* json */
        })
            .done(function (response) {
                console.log(response);
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                alert("jqXHR: " + JSON.stringify(jqXHR));
            });
        $.ajax({
            url: 'http://127.0.0.1:5050/',
            method: 'GET',
        })
            .done(function (response) {
                console.log(response);
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                alert("jqXHR: " + JSON.stringify(jqXHR));
            });
    });
</script>

3) Start the server as follows:
(base) C:\Users\ashish\Desktop>python HelloWorldServer.py

4A)
Testing using Python:
(base) C:\Users\ashish\Desktop>python HelloWorldClient.py
Response text: Hello World!
Response text: Hello, cross-origin-world!

4B)
Testing using JavaScript in browser:
Hit URL: file:///C:/Users/ashish/Desktop/HelloWorldClient.html
Check response in browser console on page load or page refresh.

4C)
For checking GET response using browser:
Enter the URL in address bar: http://127.0.0.1:5050/
The response on page: "Hello, cross-origin-world!"

Note:
If you will try to access POST resource using GET request, you will the following message:
"""Method Not Allowed
The method is not allowed for the requested URL."""

No comments:

Post a Comment