TypeScript 中的 Http 请求

新手上路,请多包涵

我试图将nodejs中的以下代码段转换为打字稿: 如何在Nodejs中进行Http请求

这是我的打字稿代码:

 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()}`);
}
}

这是我的测试代码:

 // 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);
});

如果这工作正常(我检查了 Firefox 上的链接,它返回一个纯文本随机数)我应该得到一个纯文本数字。但是,当我 console.log() 响应时,我什么也得不到。我在这里做错了什么?

原文由 Abrar Hossain 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

尽管 request-promise-native 可能工作得很好,但 Axios 是在 TypeScript 中使用的更好选择。它有自己的类型定义,总体上不太依赖其他包。使用它的 API 很像 Adrian 提供的答案,但是有一些细微的差别。

 const url: string = 'your-url.example';

try {
    const response = await axios.get(url);
} catch (exception) {
    process.stderr.write(`ERROR received from ${url}: ${exception}\n`);
}

显然,如果您希望客户端处理异常,您可以省略 try/catch 语句。

原文由 Daniel Gelling 发布,翻译遵循 CC BY-SA 4.0 许可协议

我建议使用 https://github.com/node-fetch/node-fetch

 import fetch from 'node-fetch';

const response = await fetch('https://api.github.com/users/github');
const data = await response.json();

console.log(data);

对于 POST 请求:

 import fetch from 'node-fetch';

const response = await fetch('https://bin.org/post', {method: 'POST', body: 'a=1'});
const data = await response.json();

console.log(data);

原文由 Adrian Ciura 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题