# Apelează alte servere cu REQUEST și salvează fișiere cu DOWNLOAD

> Folosește REQUEST() pentru apeluri HTTP de nivel scăzut cu control deplin asupra metodei, antetelor, query-ului și corpului, și DOWNLOAD() pentru a transmite un fișier de la distanță pe disc.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: ro
Content-SHA256: 0114539fe0a4ac668f7d6c11f3ccf1f46e30218c0c0806a9352f764ccebd9feb
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` este clientul HTTP de nivel scăzut pe care este construit `RESTBuilder`. Dă-i un obiect și folosește `await` (sau dă-i un callback ca al doilea argument). Opțiunile utile sunt `url`, `method` (implicit `GET`), `query` (un obiect, adăugat la URL), `headers`, `cookies`, `body` (un șir sau un Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` sau `raw`, care setează `content-type`), `timeout` în milisecunde și `noredirect`.

Rezultatul este un obiect cu `status`, `headers`, `cookies` și `body` (un șir; interpretează singur JSON-ul cu `.parseJSON()`). Un răspuns cu o stare de eroare precum 404 **nu** este o eroare: verifică `status`. Promisiunea este respinsă doar când eșuează cererea însăși (conexiune refuzată, timeout, host invalid).

`DOWNLOAD(url, filename)` transmite răspunsul într-un fișier și se rezolvă cu `{ status, size, filename }`. Nu se uită la stare, așa că verific-o înainte de a folosi fișierul.

```js controllers/request.js
exports.install = function() {
	ROUTE('GET /remote/', remote);
	ROUTE('POST /remote/ @json', remote_post);
	ROUTE('GET /remote/text/', remote_text);
	ROUTE('GET /call/', call);
	ROUTE('GET /download/', download);
};

function remote($) {
	$.json({ hello: 'world', name: $.query.name || null });
}

function remote_post($) {
	$.json({ received: $.body, token: $.headers['x-token'] || null });
}

function remote_text($) {
	$.plain('first line\nsecond line\n');
}

async function call($) {

	var get = await REQUEST({ url: $.hostname('/remote/'), query: { name: 'Louis' } });
	var post = await REQUEST({ method: 'POST', url: $.hostname('/remote/'), type: 'json', body: JSON.stringify({ a: 1 }), headers: { 'x-token': 'abc' } });
	var missing = await REQUEST({ url: $.hostname('/does-not-exist/') });

	var failed = null;
	try {
		await REQUEST({ url: 'http://127.0.0.1:1/' });
	} catch (e) {
		failed = true;
	}

	$.json({
		get: get.body.parseJSON(),
		post: post.body.parseJSON(),
		status: [get.status, missing.status],
		failed: failed
	});
}

async function download($) {
	var filename = PATH.tmp('forge-download.txt');
	var response = await DOWNLOAD($.hostname('/remote/text/'), filename);
	var content = require('fs').readFileSync(filename).toString('utf8');
	$.json({ status: response.status, size: response.size, content: content });
}
```
