Search code examples
node.jshttpsdynamics-crmnode-request

TypeError: Request path contains unescaped characters NodeJS + Dynamics


I am making a https.request to Dynamics CRM to fetch data for contacts in node js.

Below is my code:

var options = { path: '/api/data/v8.2/contacts?$select=address1_city,address1_line1,address1_line2,address1_line3,contactid,emailaddress1,firstname,fullname,middlename,mobilephone,statecode,suffix,telephone1,vcm_npiid,vcm_prescriberspeciality,vcm_prescriberstatus,vcm_recordtype,vcm_symphonyid&$orderby=fullname asc&$filter=statecode eq 0',
  host: 'xxxxxx.crm.dynamics.com',
  method: 'GET',
  headers:
   { Authorization: 'Bearer xxxxxxx',
     Accept: 'application/json',
     'Content-Type': 'application/json; charset=utf-8',
     Prefer: 'odata.includeannotations=OData.Community.Display.V1.FormattedValue',
     'OData-MaxVersion': '4.0',
     'OData-Version': '4.0' 
   } 
} 

var crmrequest = https.request(options, function(response) { ... }

I get this error :

TypeError: Request path contains unescaped characters

when I try without space between asc and also in eq 0 query[ by deleting it ]. It works. Any workaround


Solution

  • You have to use querystring.stringify or encodeURI in order to escape special characters.

    const querystring = require('querystring');
    const path = '/api/data/v8.2/contacts';
    const qs = {
        $select: 'address1_city,address1_line1,address1_line2,address1_line3,contactid,emailaddress1,firstname,fullname,middlename,mobilephone,statecode,suffix,telephone1,vcm_npiid,vcm_prescriberspeciality,vcm_prescriberstatus,vcm_recordtype,vcm_symphonyid',
        $orderby: 'fullname asc',
        $filter: 'statecode eq 0'
    }
    
    const options = { 
      path: path + '?' + querystring.stringify(qs),
      host: 'xxxxxx.crm.dynamics.com',
      method: 'GET'
      /* ... */
    }
    

    const path = '/api/data/v8.2/contacts';
    const query ='$select=address1_city,address1_line1,address1_line2,address1_line3,contactid,emailaddress1,firstname,fullname,middlename,mobilephone,statecode,suffix,telephone1,vcm_npiid,vcm_prescriberspeciality,vcm_prescriberstatus,vcm_recordtype,vcm_symphonyid&$orderby=fullname asc&$filter=statecode eq 0';
    
    
    const options = { 
      path: path + '?' + encodeURI(query),
      host: 'xxxxxx.crm.dynamics.com',
      method: 'GET'
      /* ... */
    }