Home > OS >  how to fetch json from API using vanilla JS through Protractor
how to fetch json from API using vanilla JS through Protractor

Time:12-06

I am trying to download distance between 2 locations from tomtom api.

Protractor will not let me use

*fetch - fetch is not defined - please use import

*import - Cannot use import statement outside of module

*when I add

{
  type: module
}

to package.json - protractor stops working, as no entire code is a module of ES

*browser.get - opens http with json data, but I cannot extract it.

Is there any other way? I tried to import json to a different file and export response.data, but the module error stops me from doing that also.

CodePudding user response:

Protractor is for testing angular webpages, but you can have the browser execute arbitrary javascript, but to use fetch, you need to use window

function getTomTomData() {
  //replace this with your tomtom api call, and transform the response
  return window.fetch(TOM_TOM_URL);
}

browser.executeScript(getTomTomData).then(res=> {
  //do something with the response
});

CodePudding user response:

I did not manage to run node-fetch on my script as Protractor kept rejecting the import. I managed to to sort it out with require 'https'

const https = require('https')
          let measureDistance = async function(pickup, dropoff) {
            let url = await    
 
 `https://api.tomtom.com/routing/1/calculateRoute/${pickup[0]},${pickup[1]}:${dropoff[0]},${dropoff[1]}/json?routeType=shortest&avoid=unpavedRoads&key=uwbU08nKLNQTyNrOrrQs5SsRXtdm4CXM`
            await https.get(url, res => {
          let body = '';
          
          res.on('data', chunk => {
              body  = chunk;
            });
            
             res.on("end", () => {
               try {
                 let json = JSON.parse(body);
                 howFar = json.routes[0].summary.lengthInMeters;
              } catch (error) {
                console.error(error.message);
              };
            }).on("error", (error) => {
              console.error(error.message);
            });
          })
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe> Also I used to put require on top of the file like in Ruby, which seemed to be another issue.

  • Related