【问题标题】:Invalid characters (non UTF-8) from node url Request but valid from browser?来自节点 url 请求的无效字符(非 UTF-8)但在浏览器中有效?
【发布时间】:2017-02-28 17:19:33
【问题描述】:

我正在使用 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));
})

但是,当从 Chrome 浏览器调用具有高棉字符的完全相同的 URL 时,我可以获得带有结果的有效 JSON。

这个问题和Request有关吗?

我该如何解决这个问题?

【问题讨论】:

  • 你能给我们看一些代码吗?
  • @IvanVasiljevic 刚刚用代码编辑了问题

标签: node.js utf-8 request google-places-api


【解决方案1】:

因此,如果您在 Chrome 中输入要向其发送请求的 URL 并打开开发工具,您将看到发送请求的原始 URL 类似于以下内容:

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

基本上 Chrome 将所有查询参数编码为 ASCII,当您直接向 URL 输入参数时,查询参数不会被编码。但是如果您通过qs 对象将参数发送到request 库,库会为您编码,您不会遇到问题。

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));
})

您可以像这样使用内置到 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));
})

为什么我认为带有qs 参数的第一个解决方案是更好的解决方案,因为库正在为您做这件事,并且所有参数都已编码。

第二种方法的更好解释可以找到here

希望这是您的问题的解决方案 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2016-07-11
    • 1970-01-01
    • 2020-07-31
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多