我一直在尝试使用Google Places API通过文本查询来获取搜索结果 .
我的URL字符串是
https://maps.googleapis.com/maps/api/place/textsearch/json?query=${textQuery}&&location=${lat},${lng}&radius=10000&key=${key}
来自浏览器的GET请求完美无缺 .
https://maps.googleapis.com/maps/api/place/textsearch/json?query=saravana stores&&location=13.038063,80.159607&radius=10000&key=${key}
上述搜索提取与查询相关的结果 .
https://maps.googleapis.com/maps/api/place/textsearch/json?query=dlf&&location=13.038063,80.159607&radius=10000&key=${key}
此搜索还会获取与dlf相关的结果 .
但是,当我尝试通过快速服务器执行相同操作时,它为不同的查询提供了相同的搜索结果 .
app.get('/findPlaces', (req, res) => {
SEARCH_PLACES = SEARCH_PLACES.replace("lat", req.query.lat);
SEARCH_PLACES = SEARCH_PLACES.replace("lng", req.query.lng);
SEARCH_PLACES = SEARCH_PLACES.replace("searchQuery", req.query.search);
https.get(SEARCH_PLACES, (response) => {
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
let places = JSON.parse(body);
const locations = places.results;
console.log(locations);
res.json(locations);
});
}).on('error', () => {
console.log('error occured');
})
});
从客户端来看,如果我第一次请求 /findPlaces?lat=13.038063&lng=80.159607&search=saravana stores
,我会得到正确的结果 . 当我尝试使用 [search=dlf]
之类的其他搜索时,它给出的结果与我从 [search=saravana stores]
获得的结果相同 . 我甚至试图用不同的查询搜索来搜索不同的lat,lng .
但是,如果我重新启动节点服务器,则会获取正确的结果 . 实际上,我无法为每个新请求重新启动服务器 .
我错过了什么吗?请帮忙 .
谢谢 .
1 回答
问题是您正在用第一个查询替换全局变量
SEARCH_PLACES
. 之后,您无法再次替换占位符,因为它们已在该字符串中替换 .例如,当应用程序启动时
SEARCH_PLACES
具有此值:在第一个请求之后,全局变量将更改为:
当第二个请求进入时,字符串中不再有任何占位符替换,因此再次返回最后一个请求 .
您希望构建URL而不必为每个请求修改全局URL: