node.js TypeScript 中的 Http 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45748476/
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
Http Request in TypeScript
提问by Abrar Hossain
I was trying to convert the following snippet in nodejs to typescript: How do I make Http Request in Nodejs
我试图将 nodejs 中的以下代码段转换为打字稿:How do I make Http Request in Nodejs
Here is my TypeScript code:
这是我的打字稿代码:
import * as http from 'http';
export class HttpRequest{
url: string;
private path: string;
private host: string;
private args: Array<Array<string>>;
constructor(url: string, args?: string){
this.url = url;
this.processUrl(this.url);
if(!!args){
this.processArgs(args);
}
this.args = [];
}
private processUrl(url: string): void {
let tld: number = url.lastIndexOf('.')
let sep: number = url.indexOf('/', tld);
this.host = url.slice(0, sep);
this.path = url.slice(sep+1);
}
private processArgs(args: string): void {
let sep: number = args.indexOf('&');
if(sep < 0){
return ;
}
let argpair: string = args.slice(0, sep);
let apsep: number = argpair.indexOf('=');
let k: string = argpair.slice(0, apsep);
let v: string = argpair.slice(apsep+1);
this.args.push([k,v]);
this.processArgs(args.slice(sep+1));
}
private preparePath(): string {
let path: string = `?`;
this.args.forEach((arg: Array<string>, i: number): void => {
let k: string = arg[0];
let v: string = arg[1];
path += k + '=' + v;
if(i == this.args.length-1){
return ;
}
path += '&';
});
return path;
}
public addArg(key: string, value: string): void {
try{
this.args.push([key,value]);
} catch(err) {
console.log(err);
}
}
public addArgs(args: Array<Array<string>>): void {
args.forEach((arg: Array<string>): void => {
this.args.push(arg);
});
}
public get(cb: (res: any) => any): void {
let opts = {
'host': this.host,
'path': `/${this.path}/${this.preparePath()}`
};
http.request(opts, (r: http.IncomingMessage): void => {
let data = '';
r.on('data', (chunk: string): void => {
console.log('Got chunk: ' + chunk);
data += chunk;
});
r.on('end', (): void =>{
console.log('Response has ended');
console.log(data);
cb(data);
});
r.on('error', (err): void => {
console.log('Following error occured during request:\n');
console.log(err);
})
}).end();
}
public test(): void {
console.log(this.preparePath());
console.log(`/${this.path}/${this.preparePath()}`);
}
}
Here is my test code:
这是我的测试代码:
// Test httpRequest
import { HttpRequest } from './httpRequest';
const request = new HttpRequest('www.random.org/integers');
request.addArg('num', '1');
request.addArg('min', '1');
request.addArg('max', '50');
request.addArg('col', '1');
request.addArg('base', '10');
request.addArg('format', 'plain');
request.addArg('rnd', 'new');
request.test();
request.get((res: string): void => {
console.log('Response received: ' + res);
});
If this works correctly (I checked the link on Firefox and, it returns a plain text random number) I should get a number as a plain text. However, when I console.log()response, I get nothing. What am I doing wrong here?
如果这工作正常(我检查了 Firefox 上的链接,它返回一个纯文本随机数)我应该得到一个纯文本数字。然而,当我console.log()回应时,我什么也得不到。我在这里做错了什么?
采纳答案by Daniel Gelling
Even though request-promise-nativeprobably works just fine, Axiosis a way better alternative for use in TypeScript. It comes with its own type definitions and is overall less dependent on other packages. Using it's API is quite like the answer provided by Adrian, however there are a few subtle differences.
尽管request-promise-native可能工作得很好,但Axios是在 TypeScript 中使用的更好替代方法。它带有自己的类型定义,并且总体上较少依赖其他包。使用它的 API 很像 Adrian 提供的答案,但是有一些细微的差异。
const url: string = 'your-url.example';
try {
const response = await axios.get(yourUrl);
} catch (exception) {
process.stderr.write(`ERROR received from ${url}: ${exception}\n`);
}
Obviously you can leave out the try/catch statement if you want the exception to be handled by the client.
显然,如果您希望客户端处理异常,则可以省略 try/catch 语句。
回答by Adrian Ciura
Use https://github.com/request/request-promise-nativelibrary.
使用https://github.com/request/request-promise-native库。
Install dependencies:
安装依赖:
npm install --save request request-promise-native
npm install --save-dev @types/request @types/request-promise-native
Then in your app:
然后在您的应用中:
import * as request from "request-promise-native";
(async () => {
const baseUrl = 'www.random.org/integers';
const queryString = '?num=100&min=1&max=100&col=5&base=10&format=html&rnd=new';
var options = {
uri: baseUrl + queryString,
};
const result = await request.get(options);
})()
回答by Er Shubham Patidar
try this :
尝试这个 :
var request = require('request');
request('www.random.org/integers, function (error, response, body) {
console.log(response.statusCode);
cb(response.statusCode);
});
Thanks!!
谢谢!!

