URL路径包含未转义的字符

时间:2016-05-07 08:02:31

标签: node.js http

我收到以下错误。我知道我需要逃避几个字符,但有没有更好的方法来做到这一点?

我的路径变量有一些错误

  getNearByUsers(latlong) {
    return http.get({
      host: 'search-vegme-user-7l3rylms73566frh4hwxblekn4.us-east-1.cloudsearch.amazonaws.com',
      path: '/2013-01-01/search?q=nikhil&expr.distance=haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude)&sort=distance asc&return=distance,displayname,profileimageurl'
    }, function(response) {
      // Continuously update stream with data
      var body = '';
      response.on('data', function(d) {
        body += d;
      });
      response.on('end', function() {

        // Data reception is done, do whatever with it!
        var parsed = JSON.parse(body);
        console.log(parsed);

      });
    });
  }


  "errors": [
{
  "message": "Request path contains unescaped characters.",
  "originalError": {}
}
  ]

1 个答案:

答案 0 :(得分:1)

您需要使用encodeURIComponent()

var value = "haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude)";
value = encodeURIComponent(value);
console.log(value); //"haversin(35.621966%2C-120.686706%2Clatlong.latitude%2Clatlong.longitude)"

改进的解决方案:Query-string encoding of a Javascript Object

serialize = function(obj) {
  var str = [];
  for(var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}

console.log("/2013-01-01/search?" + serialize({
    'q': "nikhil",
    'expr.distance': "haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude)",
    'sort': "distance asc",
    'return': "distance,displayname,profileimageurl"
}));