Pm *_*ère 3 utf-8 request node.js google-places-api
我在Node js中使用Request来调用Google Place api Web服务.请求正文出错,Invalid request. One of the input parameters contains a non-UTF-8 string.因为我在url参数(keyword参数)中使用高棉字符.
nearByUrl = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.55082623,104.93225202&radius=400&keyword=????????????&key=' + MY_KEY;
request({
url: nearByUrl,
json: true
}, function (error, response, body) {
console.log(JSON.stringify(body, null, 2));
})
Run Code Online (Sandbox Code Playgroud)
但是,当使用Chrome浏览器中的高棉字符调用完全相同的URL时,我可以获得有效的JSON结果.
这个问题与Request有关吗?
我怎样才能解决这个问题?
因此,如果您在Chrome中输入要向其发送请求的网址并打开开发工具,您会看到发送请求的原始网址与此类似:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.55082623,104.93225202&radius=400&keyword=%E1%9E%9F%E1%9F%92%E1%9E%90%E1%9E%B6%E1%9E%93%E1%9E%B8%E1%9E%99%E1%9E%94%E1%9F%92%E1%9E%9A%E1%9F%81%E1%9E%84
Run Code Online (Sandbox Code Playgroud)
基本上Chrome将所有查询参数编码为ASCII,当您直接输入参数到URL时,查询参数不会被编码.但是,如果您request通过qs对象将参数发送到库,库将为您编码它们,您将不会遇到问题的问题.
var request = require("request")
var option = {
uri: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json',
qs: {
location: '11.55082623,104.93225202',
radius: 1000,
keyword: '????????????',
key: MY_KEY
}
};
request(
option, function (error, response, body) {
console.log(JSON.stringify(body, null, 2));
})
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用构建到js库中的方法,但我个人认为第一种方法是更好的解决方案:
nearByUrl = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.55082623,104.93225202&radius=400&keyword=' + encodeURIComponent(escape('????????????')) + '&key=' + MY_KEY;
request({
url: nearByUrl,
json: true
}, function (error, response, body) {
console.log(JSON.stringify(body, null, 2));
})
Run Code Online (Sandbox Code Playgroud)
为什么我认为使用qsparam的第一个解决方案是更好的解决方案,因为库正在为您执行此操作并且所有参数都已编码.
可以在此处找到对第二种方法的更好解释.
希望这是你的问题的解决方案:)