如何在 TypeScript 中使用 RequestPromise?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40356379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use RequestPromise in TypeScript?
提问by Sergei Basharov
I have installed request-promiselibrary and trying to use it in my TypeScript app but without much luck.
我已经安装了request-promise库并尝试在我的 TypeScript 应用程序中使用它,但运气不佳。
If I use it like this:
如果我像这样使用它:
import {RequestPromise} from'request-promise';
RequestPromise('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
I see this on TS compile output:
我在 TS 编译输出上看到了这个:
error TS2304: Cannot find name 'RequestPromise'.
If I use it this way:
如果我这样使用它:
import * as rp from'request-promise';
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
I see an error that says that there is no '.then()' method on object rp.
我看到一个错误,指出对象 rp 上没有“.then()”方法。
How do I properly use it with TypeScript?
如何在 TypeScript 中正确使用它?
回答by Dave Clark
You must import all (*
) not just RequestPromise
:
您必须导入所有 ( *
) 而不仅仅是RequestPromise
:
import * as request from "request-promise";
request.get(...);
This answerelaborates on the differences between import/from
and require
.
这个答案详细说明了import/from
和之间的区别require
。
回答by Ivan Velinov
request-promise has a package for typescript
request-promise 有一个打字稿包
- npm i --save-dev @types/request-promise
- import { get, put, post } from 'request-promise';
- npm i --save-dev @types/request-promise
- 从“请求-承诺”导入 { 获取、放置、发布};
Usage
用法
get(options).then(body => {
console.log(body)
}).catch(e => reject);
回答by Kokkonda Abhilash
I use request-promise in this way
我以这种方式使用请求承诺
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) {
// Do error handling stuff
} else {
if (response.statusCode !== 200) {
// Do error handling stuff
} else {
// Do success stuff here
}
}
});