In a Raspberry Pi I use Flask to serve a web page, which uses JavaScript to post to a Python script.
Folder structure:
/home/pi/Elithion/app.py
/home/pi/Elithion/templates/index.html
/home/pi/Elithion/static/wificonfig.py
app.py (Python code using Flask)
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
index.html, JavaScript:
function ReqWifiConfig(selectedWiFiNetwork, wiFiPassword) { // Request setting the WiFi configuration
// Constants
var WifiConfigScript = '/static/wificonfig.py';
var ContentKey = 'Content-type';
var ContentVal = 'application/x-www-form-urlencoded';
// Send the wifi login credentials to the Python script using AJAX
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
...
}
else if (xmlhttp.readyState==4) {
alert(xmlhttp.status + xmlhttp.statusText);
}
}
xmlhttp.open("POST", WifiConfigScript, true);
xmlhttp.setRequestHeader(ContentKey, ContentVal);
var postData = 'nw=' + selectedWiFiNetwork + '&pw=' + wiFiPassword;
xmlhttp.send(postData);
}
This results in this alert in browser:
127.0.0.1:5000 says: 405METHOD NOT ALLOWED
and this message in the terminal:
127.0.0.1 - - (date) "POST / static/wificonfig.py HTTP/1.1 405 -
If I change "POST" to "GET", it returns the text in the script, so I know the paths are right.
I checked these StackOverflow answers, and they did not help, because I do have the right path, I am not using a HTML form, and CORS does not apply: