在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'; –