# Llama a otros servidores con REQUEST y guarda archivos con DOWNLOAD

> Usa REQUEST() para llamadas HTTP de bajo nivel con control total del método, las cabeceras, la query y el cuerpo, y DOWNLOAD() para descargar un archivo remoto al disco.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: es
Content-SHA256: 71094de2167fb86de94e9c6bc93b36f5455eeeeff1cd6849f4857d53ebb896e8
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` es el cliente HTTP de bajo nivel sobre el que está construido `RESTBuilder`. Pásale un objeto y haz `await` (o dale un callback como segundo argumento). Las opciones más útiles son `url`, `method` (por defecto `GET`), `query` (un objeto que se añade a la URL), `headers`, `cookies`, `body` (una cadena o un Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` o `raw`, que establece el `content-type`), `timeout` en milisegundos y `noredirect`.

El resultado es un objeto con `status`, `headers`, `cookies` y `body` (una cadena; interpreta el JSON tú mismo con `.parseJSON()`). Una respuesta con un estado de error como 404 **no** es un error: comprueba `status`. La promesa solo se rechaza cuando falla la propia petición (conexión rechazada, timeout, host no válido).

`DOWNLOAD(url, filename)` vuelca la respuesta en un archivo y se resuelve con `{ status, size, filename }`. No mira el estado, así que compruébalo antes de usar el archivo.

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