Exploring the process of retrieving JSON from an API using plain JavaScript within the Protractor framework

I'm attempting to retrieve the distance between two locations using the TomTom API.

Unfortunately, I am facing an issue with Protractor:

When trying to use the *fetch function - I receive an error stating "fetch is not defined" and it advises me to use import instead.

Upon attempting to use *import, another error arises: "Cannot use import statement outside of module."

After adding { type: module } to package.json, Protractor ceases to function properly as the entire code is now recognized as a module of ES.

Additionally, when utilizing *browser.get, a JSON data page opens up but I encounter difficulty extracting the information from it.

Is there an alternative method I can explore? I've tried importing the JSON to a separate file and exporting response.data, however, the module error prevents me from proceeding with this approach as well.

Answer №1

When it comes to testing angular webpages, Protractor is the tool of choice. However, you also have the flexibility to execute custom JavaScript using the browser. If you want to utilize the fetch function, make sure to access it through window.

function retrieveTomTomData() {
  // Replace this with your TomTom API call and data transformation
  return window.fetch(TOM_TOM_URL);
}

browser.executeScript(retrieveTomTomData).then(response => {
  // Process the response accordingly
});

Answer №2

I was facing difficulties running node-fetch in my script due to Protractor rejecting the import. Eventually, I resolved it by using require 'https'

const https = require('https');

let measureDistance = async function(pickup, dropoff) {
    let url = `https://api.tomtom.com/routing/1/calculateRoute/${pickup[0]}%2C${pickup[1]}%3A${dropoff[0]}%2C${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);
        });
    });
};
I also realized that putting require at the top of the file, similar to Ruby, was causing another issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Code for a succinct MySQL query in PHP using associative arrays

I'm trying to query multiple times like this: <?php $datacenter=mysqli_connect('localhost','user','pass','db'); After the DB connection, I want to count the number of votes for options 1, 2, and 3. $r11= ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

Looking to set up an event handler for the browser's back button in next.js?

When my modal opens, it adds a hash to the URL like example.com/#modal. I want to be able to recognize when the back button is clicked in the browser so I can toggle the state of the modal. The challenge is that since I am using next.js (server-side rend ...

Having trouble accessing the value of an item in a dropdown box on a website

I am currently developing a webpage using HTML5 and Knockout Js. I am facing an issue where I am unable to retrieve the ID of the selected item from a dropdown box in order to insert a value into an SQL table. As an example, consider the following SQL tab ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

The has-error class cannot be applied to certain input elements

I am currently in the process of validating some inputs within a modal: <div id="modal-section" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="m ...

Tips for simulating Axios requests in Jest

During my development process, I have implemented a function in my client/index.js file that utilizes axios to make HTTP requests import axios from "axios"; const createRequest = async (url, method) => { const response = await axios({ ...

What is the best way to establish a limit on the number of characters that can be entered into an input field in a React form?

Currently, I am creating a tool to check the strength of passwords based on their length. However, I am unsure of how to precisely determine if a password falls within specific length ranges such as "between 5 and 10 characters" or "between 20 and 30 cha ...

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

Unable to display returned data from an AJAX request made with jQuery autocomplete

After reviewing the debug developer tool, I noticed that the ajax request returned data but for some reason, the data is not being displayed in the text box. The data contains special characters which are visible in the provided image. I am trying to iden ...

Sending data between Angular and Python using both strings and JSON formats

Seeking assistance with a Python script that sends events to a server. Here is the code snippet: LOGGER = logging.getLogger("send_event") POST_EVENT_URL = "http://localhost:3000/event/" def send(name, data): url = POST_EVENT_URL + name headers = {& ...

Neglecting to pass data to the controller through the onclick function

Using this specific button element in my JavaScript implementation has raised some concerns. <button id="bid" type="button" class="button" onclick="connect()">Save</button> While I have noticed that it displays an alert message when 'ale ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

Creating a dynamic Ajax-based widget for your website: A step-by-step guide

I have a unique idea for a web widget that I want to create. This widget will need to be easily integrated into any website using javascript. It will post a form to my server, receive the data, and display the results in a small area of the host website&ap ...

Adjusting the height of the Iframe dynamically every 2 seconds

One issue I am facing is with the iframe height. When I load the iframe, it sets the height correctly and adjusts when content is loaded dynamically. However, if I reduce or delete content from the loaded page, the iframe height does not decrease (e.g., in ...

How can I implement the self-clearing feature of a timer using clearInterval in ReactJS?

I am a newcomer to the world of React and I am currently working on creating a React component with multiple features. Users can input a random number, which will then be displayed on the page. The component includes a button labeled 'start'. W ...

Sorting by two fields with varying value types in AngularJS

Need help sorting json data by two fields, prioritizing field value and then date. Check out this demo Json input [{ "title" : "Title 2", "pin" : false, "date" : 20130411204207 },{ "title" : "Title 3", "date" : 20140411204207 },{ "title" : "Title 4", ...

Could javascript be considered insufficient for conducting complex fluid simulations due to its speed limitations?

Currently, I am tackling the challenge of implementing a small fluid simulation in P5js. My attempt involved rendering 20,000 squares with random colors, but I only achieved a frame rate of 2.xxx. var sim; var xdim = 200; var xLength; var ydim = 100; var ...

In the context of ReactJS, how should the src property be formatted within an img tag to reference a mapped json file correctly?

Currently, I am trying to incorporate images from a local JSON file into my component. These images need to correspond with the data obtained from an API call. The contents of my JSON file are as follows: [ { "id": 1, "dwarf" ...

rendering json data as html using javascript

I am encountering some difficulties with displaying JSON data in HTML using JavaScript. Here is the sample JSON data: { "80": { "Id": "80", "FirstName": "Ranjan", "MiddleName": "Kumar", "LastName": "Gupta", "Gender": "Male", "Locat ...