J'essayais de convertir le fragment de code suivant dans nodejs en TypeScript: Comment puis-je créer une requête HTTP dans Nodejs
Voici mon code TypeScript:
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()}`);
}
}
Voici mon code de test:
// 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);
});
Si cela fonctionne correctement (j'ai vérifié le lien sur Firefox et, il renvoie un nombre aléatoire de texte brut), je devrais obtenir un nombre sous forme de texte brut. Cependant, lorsque je console.log()
réponse, je ne reçois rien. Qu'est-ce que je fais mal ici?
Utilisez la bibliothèque https://github.com/request/request-promise-native .
Installer:
npm install --save request
npm install --save request-promise-native
Puis dans votre application:
import * as request from "request-promise-native";
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);