简体   繁体   English

将数据从html发送到pythonflask服务器“GET/HTTP/1.1”405错误

[英]Sending data from html to python flask server "GET / HTTP/1.1" 405 error

very new to python/AJAX and have been piecing everything from examples on the internet/flask documentation and I've gotten so far.对 python/AJAX 来说非常新,并且已经从 Internet/flask 文档上的示例中拼凑了所有内容,到目前为止我已经得到了。 Basically what I am trying to do is send latitude and longitude coordinates on a click (from mapbox API) to flask, and have that data print to console (to prove it has successfully gone Flask so I can work with it later).基本上我想要做的是通过点击(从 mapbox API)将纬度和经度坐标发送到烧瓶,并将该数据打印到控制台(以证明它已成功进入 Flask,以便我以后可以使用它)。

data I am trying to send is formatted as:我尝试发送的数据格式为:

LngLat {lng: 151.0164794921875, lat: -33.79572045486767}

HTML: HTML:

<button onclick=submit() type="button">POST</button>

<script>    
map.on('click', function (e) { 
console.log(e.lngLat)
});

function submit() {
var myData = e.lngLat
$.post( "/", $( "myData" ).serialize() 
);
}
</script>

PY:派:

from flask import Flask
from flask import request
from flask import render_template

app = Flask(__name__)

@app.route('/', methods=['POST'])
def home():
return render_template('index.html')
print(request.form['myData'])

if __name__ == '__main__':
app.run(debug=True)

when I try to run from console to localhost:5000 I get the error当我尝试从控制台运行到 localhost:5000 时出现错误

127.0.0.1 - - [23/Sept/2016 23:21:15] "GET / HTTP/1.1" 405 - 

I'm sorry if this is a silly question but I'm stumped for now!如果这是一个愚蠢的问题,我很抱歉,但我现在很难过! Thank you for your input谢谢您的意见

In your route, allow GET method, otherwise the html wil never render.在您的路线中,允许GET方法,否则 html 将永远不会呈现。

@app.route('/', methods=['POST', 'GET'])

To print lat/lng to the console, first check if the method is POST , then print it:要将 lat/lng 打印到控制台,首先检查方法是否为POST ,然后打印它:

if request.method == 'POST':
    print(request.form.get('lng'), request.form.get('lat'))

This is the resulting code for the route:这是路线的结果代码:

@app.route('/', methods=['POST', 'GET'])
def home():
    if request.method == 'POST':
        print(request.form.get('lng'), request.form.get('lat'))
    return render_template('index.html')

The reason you are getting 405 error is because you only have home() controller, that accept only POST methods.您收到 405 错误的原因是因为您只有home()控制器,该控制器仅接受POST方法。 And you are trying to get response with GET method.并且您正在尝试使用GET方法获得响应。

So you need to change methods argument in @app.route() decorator所以你需要改变@app.route()装饰器中的methods参数

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('index.html')

But still, you don't have any code that would handle your AJAX request.但是,您仍然没有任何代码可以处理您的 AJAX 请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM