gpt4 book ai didi

javascript - Flask - 监听 POST 请求

转载 作者:行者123 更新时间:2023-11-30 11:40:28 25 4
gpt4 key购买 nike

我正在使用 Flask 来检索用 javascript 生成的坐标值。 flask 代码:

from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify


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


@app.route('/postmethod', methods = ['GET', 'POST'])
def get_post_location():
where = request.form['location']
return where

控制台日志:

XHR 完成加载:POST "http://127.0.0.1:5000/postmethod".

JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>

<meta charset="utf-8">

<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>

<body>

<div id="map"></div>

<script>

function initMap() {
var pos;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});

// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(pos)

infoWindow.setPosition(pos);
infoWindow.setContent('You are here.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});

$.ajax({
type: "POST",
url: "/postmethod",

// set content type header to use Flask response.get_json()
contentType: "application/json",

// convert data/object to JSON to send
data: JSON.stringify({location: pos}),

// expect JSON data in return (e.g. Flask jsonify)
dataType: "json",

// handle response
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});

} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());

}
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}

</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBr8V0XkaNFYkNXcP6eJc76b6YutvizwNw&callback=initMap">
</script>
<form action="/postmethod", method="post">
</form>
</body>
</html>

问题:

我如何收听这个,以便我可以将 where 发送到其他脚本?

编辑:

完整回溯(在 PJ 的回答之后我做了 get_json(silent=False)

127.0.0.1 - - [19/Mar/2017 23:20:26] "GET /geo HTTP/1.1" 200 -
data: {}
127.0.0.1 - - [19/Mar/2017 23:20:27] "POST /postmethod HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/vitorpatalano/Documents/Code/Apps/App/app/app.py", line 134, in get_post_location
where = data['location']
KeyError: 'location'

最佳答案

此问题与您将数据从 javascript 发送到 Flask 的方式有关。编码后的“位置”信息不是字符串值,而是对象或 JSON。

所以,您真正想要做的是在 Javascript 和 Flask 之间来回发送信息 (JSON)

下面是实现方法。而不是 jQuery $.post()您需要使用 $.ajax() 的方法直接方法。

更新:将我的代码更新为我本地机器上的完整工作示例。 $.ajax() 方法被调用得太早...需要将其移动到地理定位服务的调用范围内。

关于链接和管理异步调用流的另一件事是 Promise图书馆。

Javascript/HTML:

<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta charset="utf-8">
<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
#map {height: 100%;}
html, body {height: 100%;margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="map"></div>
<script>

function initMap() {
var pos = {},
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
}),
infoWindow = new google.maps.InfoWindow({map: map});

// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};

infoWindow.setPosition(pos);
infoWindow.setContent('Smells like coffee...');
map.setCenter(pos);

$.ajax({
type: "POST",
url: "/postmethod",
contentType: "application/json",
data: JSON.stringify({location: pos}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});

}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}

</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBr8V0XkaNFYkNXcP6eJc76b6YutvizwNw&callback=initMap">
</script>
</body>
</html>

在 Flask 中,您现在可以使用 get_json()方法将重现您在 python 中用 javascript 编码的数据结构。你应该使用 Flask jsonify()将响应返回给您的 javascript 调用。

python :

@app.route('/postmethod', methods=['POST'])
def postmethod():
data = request.get_json()
print data
return jsonify(data)

关于javascript - Flask - 监听 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com