nchaulet / node-geocoder

nodejs geocoding library
http://nchaulet.github.io/node-geocoder/
MIT License
928 stars 214 forks source link

Fix Agolgeocoder JSON conversion from httpadapter #284

Closed Honga1 closed 2 years ago

Honga1 commented 4 years ago

What

This PR removes the double conversion of JSON strings from the request response to ARCGIS queries. It also updates it's tests to a valid-passing status.

Why

Running the example:

import NodeGeocoder from 'node-geocoder';

import { ARCGIS_CLIENT_ID, ARCGIS_CLIENT_SECRET } from './config';

var options: NodeGeocoder.AgolOptions = {
  provider: 'agol',
  client_id: ARCGIS_CLIENT_ID,
  client_secret: ARCGIS_CLIENT_SECRET,
};

var geocoder = NodeGeocoder(options);

// Using callback
geocoder.geocode('29 champs elysée paris', function(err: any, res: any) {
  console.log(res);
});

// Or using Promise
geocoder
  .geocode('29 champs elysée paris')
  .then(function(res: any) {
    console.log(res);
  })
  .catch(function(err: any) {
    console.log(err);
  });

Throws error

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at C:\Users\USERNAME\ra-map\node_modules\node-geocoder\lib\geocoder\agolgeocoder.js:122:21
    at IncomingMessage.<anonymous> (C:\Users\jaepe\ra-map\node_modules\node-geocoder\lib\httpadapter\httpadapter.js:66:9)
    at IncomingMessage.emit (events.js:185:15)
    at IncomingMessage.emit (domain.js:421:20)
    at endReadableNT (_stream_readable.js:1106:12)
    at process._tickCallback (internal/process/next_tick.js:114:19)

Which is caused by:

lib\geocoder\agolgeocoder.js

    _this.httpAdapter.get(_this._endpoint, params, function(err, result) {
      result = JSON.parse(result);

And

lib\httpadapter\httpadapter.js

      if (contentType !== undefined && contentType.indexOf('application/json') >= 0) {
        callback(false, JSON.parse(str));
      } else {
        callback(false, str);
      }

Which is due to the header response from ARCGIS: 'content-type': 'application/json;

{ date: 'Tue, 17 Dec 2019 16:17:24 GMT',
  'content-type': 'application/json;charset=UTF-8',
  'content-length': '500',
  connection: 'close',
  'x-content-type-options': 'nosniff',
  'x-xss-protection': '1; mode=block',
  server: '',
  etag: '54b33e50',
  'cache-control': 'max-age=300',
  'x-cached': 'HIT',
  vary: 'Origin,Accept-Encoding' }
nchaulet commented 2 years ago

httpadapter do not exists anymore I think that PR is not relevant anymore, feel free to reopen it if you think it's still an issue