# Volajte iné servery cez REQUEST a ukladajte súbory cez DOWNLOAD

> Použite REQUEST() na nízkoúrovňové HTTP volania s plnou kontrolou nad metódou, hlavičkami, query a telom a DOWNLOAD() na stiahnutie vzdialeného súboru na disk.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: sk
Content-SHA256: 288c221fb089f3675491b89cca48bd0cde9a085252dc040e73fd46072b044316
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` je nízkoúrovňový HTTP klient, na ktorom je postavený `RESTBuilder`. Odovzdajte mu objekt a použite `await` (alebo mu dajte callback ako druhý argument). Užitočné možnosti sú `url`, `method` (predvolene `GET`), `query` (objekt pripojený k URL), `headers`, `cookies`, `body` (reťazec alebo Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` alebo `raw`, ktorý nastaví `content-type`), `timeout` v milisekundách a `noredirect`.

Výsledkom je objekt so `status`, `headers`, `cookies` a `body` (reťazec; JSON si spracujte sami cez `.parseJSON()`). Odpoveď s chybovým stavom ako 404 **nie je** chyba: skontrolujte `status`. Promise sa zamietne iba vtedy, keď zlyhá samotná požiadavka (odmietnuté spojenie, timeout, neplatný hostiteľ).

`DOWNLOAD(url, filename)` streamuje odpoveď do súboru a vyrieši sa s `{ status, size, filename }`. Stav nekontroluje, preto ho overte pred použitím súboru.

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