通过Express向Google Places API进行远程请求每次都会得到重复的结果



我一直在尝试使用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相关的结果。

但是,当我尝试通过express服务器进行同样的操作时,它会为不同的查询提供相同的搜索结果。

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。

但是,如果我重新启动节点服务器,就会得到正确的结果。实际上,我不能为每个新请求重新启动服务器。

我是不是错过了什么?请帮忙。

谢谢。

问题是您要用第一个查询替换全局变量SEARCH_PLACES。之后,您将无法再次替换占位符,因为它们已经在该字符串中被替换。

例如,当应用程序启动时,SEARCH_PLACES具有以下值:

https://maps.googleapis.com/maps/api/place/textsearch/json?query=searchQuery&location=lat,lng&radius=10000

第一次请求后,全局变量将更改为:

https://maps.googleapis.com/maps/api/place/textsearch/json?query=foo&location=13,37&radius=10000

当第二个请求出现时,字符串中不再有任何占位符可替换,因此最后一个请求将再次返回。


您希望在不修改每个请求的全局URL的情况下构建URL:

const SEARCH_PLACES = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
app.get('/findPlaces', (req, res) => {
const { lat, lng, search } = req.query
let url = `${SEARCH_PLACES}?query=${search}&location=${lat},${lng}`
https.get(url, (res) => {
// ...
})
})

最新更新