Python code -
from flask import Flask
from flask_cors import CORS
import cgi
app = Flask(__name__)
CORS(app)
form = cgi.FieldStorage()
var1 = form.getvalue('var1')
@app.route("/", methods=['GET', 'POST'])
def apicall():
if len(var1)>1:
return 'received value from JS function'
if __name__ == "__main__":
app.run()
error-: TypeError: object of type 'NoneType' has no len().- "POST / HTTP/1.1" 500 -
My javascript function -
function callPythonScript() {
alert("called_python_script");
$.ajax({
url: "http://127.0.0.1:5000",
type: "POST",
data:{
var1: window.location.href,
},
success: function(response) {
console.log(response);
},
error: function(xhr) {
console.log(xhr);
}
do i need configure my flask server to accept values from js func, what i have tried is -
import cgi
form = cgi.FieldStorage()
var1 = form.getvalue('var1')
PS: this setup works perfectly if i just pass return "Hello world" in python funx apicall()
var1 = form.getvalue('var1')
inside the body ofapicall()
and you have to only use that code when you have aPOST
method@app.route("/", methods=['GET','POST']) def apicall(): var1 = None if request.method == "POST": var1 = form.getvalue('var1') if len(var1)>1: return 'received value from JS function'