Can someone show me how to implement RequestPromise in TypeScript?

I recently integrated the request-promise library into my TypeScript project, but I am facing some challenges in utilizing it effectively.

When attempting to use it in the following manner:

import {RequestPromise} from 'request-promise';

RequestPromise('http://www.google.com')
        .then(function (htmlString) {
            // Processing html...
        })
        .catch(function (err) {
            // Crawling failed...
        });

I encounter the following error during compilation:

error TS2304: Cannot find name 'RequestPromise'.

Alternatively, if I try using it like this:

import * as rp from 'request-promise';

rp('http://www.google.com')
    .then(function (htmlString) {
        // Processing html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

An error is thrown indicating that there is no '.then()' method on the object rp.

Can someone provide guidance on the correct way to implement request-promise with TypeScript?

Answer №1

To properly utilize the functionality, make sure to import everything (not just RequestPromise):

import * as request from "request-promise";
request.get(...);

This explanation provides more insight on the variances between import/from and require.

Answer №2

Utilize request-promise's TypeScript package

npm install --save-dev @types/request-promise
import { get, put, post } from 'request-promise';

How to Use

get(options).then(body => {

    console.log(body)

}).catch(e => reject);

Answer №3

This is how I implement request-promise:

import * as requestPromise from 'request-promise';

const options = {
    uri: _url,
    proxy: https://example.host.com:0000,
    headers: {
        Authorization: 'Bearer ' + token
    }
};

requestPromise.get(options, (error, response) => {
    if (error) {
        // Handle errors here
    } else {
        if (response.statusCode !== 200) {
             // Handle error responses
        } else {
             // Implement success logic here
        }
    }
});

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

Transmitting an HTML file along with JSON data and enabling the browser to refresh the JSON data without reloading the entire

I'm currently working on a project involving a browser-server program where the browser sends an http get request to ''. The server is expected to return both an HTML page and a JSON response. I attempted using res.render(), passing the JSON ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Require assistance with accurately inputting a function parameter

I developed this function specifically for embedding SVGs export function svgLoader( path: string, targetObj: ElementRef ){ let graphic = new XMLHttpRequest; graphic.open('GET', path, !0), graphic.send(), graphic.onload = (a)=> ...

There seems to be an issue with node.js - headers cannot be set after they have already been sent to

As I work on developing my blog, I've encountered an issue with rendering different paths using the router parameter. Each time I attempt to display another route, an error surfaces. Unfortunately, I'm unable to provide more details at this momen ...

Button on aspx page not functioning properly when clicked

I seem to be experiencing an issue with buttons. To check if the function is being triggered, I used alert("") and found that it does enter the function when the button is clicked. However, after the alert, any other code inside the function seems to not w ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Trouble with transmitting props to function

The child component is not receiving the props as expected. When printed, it displays an empty object. The problem seems to be in the News.js file specifically related to passing props to the child component from App.js. All functions are operational excep ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

In JavaScript, a nameless function is being returned within another nameless function

Can the getNameFun function just return this.name instead of an anonymous function? Is there a reason for this structure? Code Segment 1: var name = "The Window";   var object = {     name : "My Object",     getNameFunc : function(){ ...

Having trouble with the post request in Express JS and Vue? Don't worry, we've got you covered

I've been following a tutorial to set up a basic app and everything is working smoothly, except for the post request which seems to be causing me trouble. Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY Although the issue is reproducible based ...

Difficulty: Issue with displaying Backbone collection using Mustache template

I'm new to backbone js and Mustache. I want to load a backbone collection on page load from rails json object to avoid making an extra call. However, I'm facing issues when trying to render the backbone collection using a mustache template. Here ...

Exploring the Depths of the DOM: Enhancing User Experience with Jquery

I am facing an issue with my AJAX request in my page. After retrieving data from the database and trying to append it to a div, I am attempting to create an accordion interface without success. Below is a snippet of my source code after the AJAX call: ...

When using VSCode for Next.js projects, automatic imports from "react" are not supported

* While similar, this question is not a duplicate of this other question; the solutions provided there are tailored for TypeScript and do not seem to apply to JavaScript. In my current project using Next.js in Visual Studio Code, I am facing an issue wher ...

Manipulate documents in a Mongoose array by conditionally adding or removing elements

Upon receiving data from the front end, I am dealing with the following object: { name: "Test 1", sets: [1,2] } Mongo Schema: Sets name: { type: String }, tests : [{ type: Schema.Types.ObjectId, ref : 'Test' ...

Enhancing the functionality of the onclick function within the ng-repeat by incorporating a scope

I am looking to pass a parameter to a function that is called via onclick within an ng-repeat: <!-- Sliding bar (bottom) --> <div ng-show="currentSVG && currentLanguage && currentWidth && bannerHeight" pageslide ps-open=" ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

Forcing the Empty Table message in jQuery DataTables post an AJAX request

My configuration for jquery-datatables includes a custom search filter that acts as both the standard keyword filter and a specific Item ID search using an ajax call to retrieve a value from the back end, which is then used to search a particular column in ...

Is it possible to activate or deactivate a button depending on a radio button selection using jQuery?

Below is the code I have written in an aspx file: <asp:Button ID="btn" runat="server" Text="Add As a Sub Organization" OnClick="lnkChild_Click" ValidationGroup="GroupA" class="btn-u" CausesValidation="true" /> <asp:GridView ID="grdDuplicateO ...

Delivering static assets through a POST request with express.js

I'm having an issue serving static content for a Facebook app using express.js app.configure(function (){ app.use('/', express.static(__dirname + '/public')); }); Everything is working fine with a GET request, but when I try ...