非 UTF-8 字符串错误 public 域但不是本地主机

non-UTF-8 string error public domain but not lcoalhost

我正在使用 GOOGLE API 来获取几何值。

这是我的一段代码:

const utf8 = require('utf8');

apiCreateShop.post('/', function(request, response) {

if (request.query.street && request.query.street_number && request.query.city && request.query.country && request.query.name && request.query.vendorID && request.query.description) {
        
        var url = utf8.encode('https://maps.googleapis.com/maps/api/geocode/json?address=' + request.query.street + ' ' + request.query.street_number + ' ' + request.query.city + ' ' + request.query.country + '&key=key');
        
        var lat = "";
        var lng = "";
        http.get(url, (res) => {
            let body = "";
            res.on("data", (chunk) => {
                body += chunk;
            });
            res.on("end", () => {
                try {
                    let json = JSON.parse(body);
                    lat = json['results'][0].geometry.location['lat'];
                    lng = json['results'][0].geometry.location['lng'];

如果我使用 POSTMAN 调用 API 到我的本地开发环境,我会成功。

将代码部署到我的测试实例(域)时失败,出现以下错误:

error_message: 'Invalid request. One of the input parameters contains a non-UTF-8 string.',

错误是参数中传递的街道“Ü”。

{ "message": "No data found" } //return if exception

我试过了

utf8.encode(string)

但它不起作用。这里有什么问题?

如此处所示,URL 无效。 RFC 3986 定义每个组件中允许使用的字符。在查询组件中,只允许以下内容:

  query       = *( pchar / "/" / "?" )
  pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
  unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
  pct-encoded = "%" HEXDIG HEXDIG
  sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

基本上,“拉丁语、0-9 和一些符号”的表达方式很长。 Ü 不在该列表中。 URLs 不是 UTF-8 编码的。它们是 US-ASCII 编码的(即“7 位 ASCII”)。

您需要对其他值进行百分比编码。所以 Ü 应该是 %C3%9C.

不同的组件有不同的规则。

有些服务器对它们接受的内容很草率,因此有时原始 UTF-8 会“起作用”。但它是无效的,并非所有服务器都会接受它。