Encountering a JS error while attempting to execute a basic HTTP request

I'm currently attempting to interact with a Gateway and decided to test out the https://www.npmjs.com/package/@types/request module.

Below is the snippet of code I am trying to execute:

export class OAuthAccessor {

    //some stuff

    public static createOAuthAccessToken() {
        this.makeCall();  //this line 11
    }

    private static makeCall() {
        var request = require('request');
        request.post({
            uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
            headers: {
                "Accept": "application/json",
                "Accept-Language": "en_US",
                "content-type": "application/x-www-form-urlencoded"
            },
            auth: {
                'user': this.clientID,
                'pass': this.secret,
                // 'sendImmediately': false
            },
            form: {
                "grant_type": "client_credentials"
            }
        }, function(error, response, body) {
            console.log("error = " + error);
            console.log(body);
        });
    }

}

Error Message:

file:///.../OAuthAccessor.js:11:30: JS ERROR Error: Could not find module 'request'. Computed path '/Users/admin/Library/Developer/CoreSimulator/Devices/ACA260DA-C0FD-4373-8822-447422199751/data/Containers/Bundle/Application/EE654C43-B629-4817-929F-F4E52DA1A99F/IPGIntegration.app/app/tns_modules/request'

Contents of My Package.json file:

{
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.IPGIntegration",
    "tns-ios": {
      "version": "3.1.0"
    },
    "tns-android": {
      "version": "3.1.1"
    }
  },
  "dependencies": {
    "@types/request": "^2.0.0",
    "nativescript-theme-core": "~1.0.2",
    "require": "^2.4.20",
    "tns-core-modules": "~3.1.0"
  },
  "devDependencies": {
    "babel-traverse": "6.25.0",
    "babel-types": "6.25.0",
    "babylon": "6.17.4",
    "lazy": "1.0.11",
    "nativescript-dev-typescript": "~0.5.0",
    "typescript": "~2.3.4"
  }
}

Details in My tsconfig.json file:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noEmitHelpers": true,
        "noEmitOnError": true,
        "lib": [
            "es6",
            "dom"
        ],
        "baseUrl": ".",
        "paths": {
            "*": [
                "./node_modules/tns-core-modules/*",
                "./node_modules/@types/request/*"
            ]
        }
    },
    "exclude": [
        "node_modules",
        "platforms",
        "**/*.aot.ts"
    ]
}

Steps taken so far: I initiated a new Project using the typescript template

tns create my-app-name --template typescript
npm install typescript (version 2.3.4)
npm install @types/request

I've attempted re-installing typescript, types/request module, and node_modules folder multiple times, including testing other versions of typescript. Is there something crucial that I might have overlooked during the installation process of that module?

Answer №1

To avoid using the request npm module, which relies on built-in node functionalities like the net module in nodeJS, consider utilizing cross-platform modules such as the http implementation outlined in the NativeScript documentation at .

If your requirements involve making https requests, you may want to explore the nativescript-https plugin available at https://www.npmjs.com/package/nativescript-https

Answer №2

perhaps you could attempt to

<pre>import { Request } from '@types/request'
</pre>

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

Transforming a Formdata object into a JavaScript array

Greetings everyone! Is there a way in JavaScript to convert this data structure: { Control[0].Eseguito: "true" Control[0].Id:"2" Control[0].Nota:"" Control[1].Eseguito: "true" Control[1].Id:"2" Contr ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

Is it possible to load JavaScript code once the entire page has finished loading?

My webpage includes a script loading an external JavaScript file and initiating an Ajax query. However, the browser seems to be waiting for example.com during the initial page load, indicating that this external dependency may be causing a delay. Is there ...

Retrieving Dates with Timezone Offsets in MongoDB using JavaScript and Node.js

When retrieving dates from a Mongo database, a common issue arises due to the difference between UTC timestamps stored in the database and how JavaScript handles Date objects, accounting for timezone offsets. This often results in discrepancies like: For ...

Slight Misalignment of Elements

I am attempting to align two corners of an element so that they perfectly match the corners of another element. In simpler terms, I am aiming to synchronize the corners of one element with those of another element. Below is the code snippet: ... When y ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

Suggestions for autocomplete in a textarea within an HTML element

<!DOCTYPE html> <html> <head> <base href="http://demos.telerik.com/kendo-ui/autocomplete/index"> <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style> <title></title> ...

Check if the number field in the If statement is empty or contains an excessive number of decimal places, while excluding cases where only zeroes are present in the decimal places

I am currently working with the following line of code: if ($val === "" || ($val.split(".")[1] || "").length > 2) With some assistance from the helpful individuals here, I have managed to implement this code successfully. ...

What is the process for duplicating a group containing loaded .obj models?

Initially, I created a new THREE.Object3D() and named it groupChair. I then loaded 3 obj files and added them to groupChair within the callback function. After that, I added the groupChair to the scene and it worked perfectly. However, I encountered an iss ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

Transform JSON data into an HTML table display using JavaScript/JQuery

To retrieve the JSON output on the user interface, I use the following function: $("#idvar").click(function(){ var d1 = document.getElementById("dText"); var d2 = document.getElementById("dJson"); var mytext = d1.textContent; alert(mytext); $.po ...

When clicking on the dropdown items of another button, the class of the child element in the Bootstrap button dropdown is being removed

Check out the JSFiddle for this code snippet. I'm attempting to implement Bootstrap's drop-down menu using list items instead of options. When a list item is selected, the data should be retrieved and displayed as an active selection within a bu ...

AngularJS filtering with multiple conditions

My ng-repeat list is currently displaying a collection of objects with a filter applied to only show objects inserted today. Here is how it looks: <div class="row msf-row" ng-repeat="record in recordlist | filter: record.date = dateJson"> Whi ...

Utilizing React with Typescript to Implement useReducer with Action Interface Featuring Union Type Support

My current challenge involves creating a reducer using the useReducer hook. I have defined an interface named Action which includes a property that can hold either a string or a number: type Actions = 'update_foo' | 'update_bar'; inter ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

Animating content through CSS and jQuery to reveal its unfolding effect

Just stumbled upon the amazing quote-expansion animation in the OSX Mail app and I am completely impressed. I am on a mission to bring that same magic to the web (or at least close to it), but unsure if anyone has done something similar yet. A couple of ...

A guide to saving an ArrayBuffer as a file using JavaScript

I am currently developing a file uploader for the Meteor framework. The approach involves breaking down the file on the client side from an ArrayBuffer into small packets of 4096 bits, which are then sent to the server through a Meteor.method. The abridge ...

Displaying only a section of a webpage using AJAX

Currently, I am utilizing an ajax call to showcase a PHP page, which is functioning correctly as shown below: <script type="text/javascript"> var xhr = false; if (window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); ...