在Raspberry Pi中,我使用Flask提供一个网页,该网页使用JavaScript发布到Python脚本。“GET”获取脚本文本,“POST”导致“405方法不允许”,我_did_ methods = ['GET','POST'](从JavaScript通过Flask到Python)
文件夹结构:
/home/pi/Elithion/app.py
/home/pi/Elithion/templates/index.html
/home/pi/Elithion/static/wificonfig.py
app.py(瓶使用Python代码)
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);
}
这导致该警报的浏览器:
127.0.0.1:5000 says: 405METHOD NOT ALLOWED
,这消息在终端:
127.0.0.1 - - (date) "POST/static/wificonfig.py HTTP/1.1 405 -
如果我改变“POST”到“GET”,则返回在脚本中的文本,所以我知道的路径是正确的。
我检查这些StackOverflow的答案,他们没有帮助,因为我有正确的道路,我没有使用HTML表单,和CORS不适:
- Sending POST Data through Flask
- POST 405 (Method Not Allowed)
- Flask - POST Error 405 Method Not Allowed
- Method Not Allowed flask error 405
- method not allowed error in flask。
当你的路由只是'/'时,你为什么要发布到'/static/wificonfig.py'? –
因为这就是脚本的位置,这就是Flask希望你放置文件(图像等)的地方。现在,如果我应该把脚本放在其他地方,我很想学习。你认为这是我的问题吗? –
@Daniel Roseman,因为如果我将脚本移动到/ home/pi/Elithion /,并将该行更改为WifiConfigScript ='/wificonfig.py';我得到了404。我也尝试过var WifiConfigScript ='wificonfig.py';和var WifiConfigScript ='Elithion/wificonfig.py'; –