# Chiamare altri server con REQUEST e salvare file con DOWNLOAD

> Usa REQUEST() per chiamate HTTP di basso livello con pieno controllo su metodo, header, query e corpo, e DOWNLOAD() per scaricare un file remoto su disco.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 488ffb145634759c472c2df25eef8337519a41312bf0c7239171bb9cacfb7f75
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` è il client HTTP di basso livello su cui è costruito `RESTBuilder`. Passagli un oggetto e usa `await` (oppure dagli una callback come secondo argomento). Le opzioni utili sono `url`, `method` (predefinito `GET`), `query` (un oggetto, aggiunto all'URL), `headers`, `cookies`, `body` (una stringa o un Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` o `raw`, che imposta `content-type`), `timeout` in millisecondi e `noredirect`.

Il risultato è un oggetto con `status`, `headers`, `cookies` e `body` (una stringa; interpreta il JSON da solo con `.parseJSON()`). Una risposta con uno stato di errore come 404 **non** è un errore: controlla `status`. La promise viene rifiutata solo quando fallisce la richiesta stessa (connessione rifiutata, timeout, host non valido).

`DOWNLOAD(url, filename)` scrive la risposta in streaming in un file e si risolve con `{ status, size, filename }`. Non guarda lo stato, quindi controllalo prima di usare il file.

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