---
title: Controller
project: Total.js V4
version: 0.0.99
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/controller/
updated: 2026-11-16T15:41:00.817Z
---

# Controller

> Proprietà e metodi del controller, l'oggetto che risponde a una richiesta.

Il controller è `this` dentro ogni azione di una route. Contiene i dati della richiesta e i metodi che rispondono alla richiesta. La guida [Controller](../../guides/controllers/) spiega come usarlo con esempi; questa pagina è il riferimento esatto.

## API

### controller.body

Type: `property`

Il corpo della richiesta già analizzato.

Returns: `Object`

Un corpo JSON o URL-encoded viene analizzato in un oggetto. I valori di un form sono stringhe. Una route con uno schema lo sostituisce con il modello validato. Puoi anche assegnare un nuovo oggetto.

Example: Leggere il corpo
```js
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact() {
	var email = this.body.email;
	this.success();
}
```

### controller.query

Type: `property`

La query string dell'URL come oggetto.

Returns: `Object`

I valori sono stringhe: `?page=2` dà `{ page: '2' }`. L'oggetto viene analizzato la prima volta che lo leggi.

Example: Paginazione
```js
function list() {
	var page = (this.query.page || '1').parseInt();
	this.json({ page: page });
}
```

### controller.params

Type: `property`

I parametri dinamici dell'URL.

Returns: `Object`

Ogni `{name}` della route diventa una chiave. I parametri dichiarati con un tipo vengono convertiti: `{id:number}` con `parseInt()`, `{active:boolean}` con `parseBoolean()` e `{date:date}` con `parseDate()`. Gli stessi valori arrivano come argomenti dell'azione.

Example: Parametro tipizzato
```js
exports.install = function() {
	ROUTE('GET /orders/{id:number}/', order);
};

function order(id) {
	// this.params.id is a number
	this.json({ id: this.params.id });
}
```

### controller.files

Type: `property`

I file caricati.

Returns: `Array`

Solo le route con il flag `upload` ricevono file. Ogni file ha `name` (il campo del form), `filename`, `type`, `size`, `extension`, `width` e `height`, e i metodi `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` e `isAudio()`. `move()`, `copy()` e `read()` restituiscono una promise senza callback. I file temporanei vengono rimossi quando la richiesta termina, a meno che tu non chiami `controller.autoclear(false)`.

Example: Salvare un upload
```js
exports.install = function() {
	ROUTE('POST /upload/', upload, ['upload'], 1024 * 5);
};

async function upload() {
	var file = this.files[0];
	await file.move(PATH.public('uploads/' + file.filename));
	this.success();
}
```

### controller.user

Type: `property`

L'utente autenticato.

Returns: `Object`

L'oggetto che il tuo delegato `AUTH()` ha passato a `$.success(user)`. È `undefined` quando nessuno è autenticato. Puoi assegnarlo.

Example: Profilo
```js
exports.install = function() {
	ROUTE('+GET /api/profile/', profile);
};

function profile() {
	this.json({ name: this.user.name });
}
```

### controller.headers

Type: `property`

Gli header della richiesta.

Returns: `Object`

I nomi degli header sono in minuscolo.

Example: Leggere un header
```js
function api() {
	var token = this.headers['x-token'];
	this.plain(token ? 'ok' : 'missing');
}
```

### controller.ip

Type: `property`

L'indirizzo IP del client.

Returns: `String`

Dietro un proxy è il primo indirizzo dell'header `X-Forwarded-For`; altrimenti l'indirizzo della connessione.

### controller.url

Type: `property`

Il percorso dell'URL della richiesta in minuscolo.

Returns: `String`

Non ha query string e termina sempre con `/`.

### controller.mobile

Type: `property`

`true` quando il client è un dispositivo mobile.

Returns: `Boolean`

Viene verificato sull'header `User-Agent`. Puoi assegnarlo.

### controller.xhr

Type: `property`

`true` quando la richiesta è stata inviata da XMLHttpRequest.

Returns: `Boolean`

È `true` quando la richiesta ha l'header `X-Requested-With: XMLHttpRequest`.

### controller.language

Type: `property`

La lingua della richiesta.

Returns: `String`

È il valore restituito dal tuo delegato di localizzazione (`DEF.onLocale`). Le viste e `controller.mail()` traducono i testi con essa.

### controller.status

Type: `property`

Il codice di stato HTTP della risposta.

Returns: `Number`

Impostalo prima di rispondere. `json()`, `jsonstring()`, `plain()`, `content()` e `html()` lo usano, e usano `200` quando non è impostato. `invalid()` usa uno stato superiore a `399` per gli errori.

Example: Creato
```js
function create() {
	this.status = 201;
	this.json({ id: UID() });
}
```

### controller.repository

Type: `property`

Un oggetto condiviso dalla vista e dal suo layout.

Returns: `Object`

I valori che salvi qui prima di `view()` sono disponibili nella vista e nel layout come `repository`. Vi vengono salvati anche il titolo della pagina e i meta tag.

Example: Passare un valore al layout
```js
function home() {
	this.repository.menu = 'home';
	this.view('index');
}
```

### controller.exception

Type: `property`

Il problema di una route di errore.

Returns: `Error|String`

In una route per uno stato di errore (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) contiene il problema passato a `throw404()`, `throw500()` e agli altri.

### controller.req

Type: `property`

L'oggetto richiesta del framework.

Returns: `Request`

Estende la richiesta di Node.js. Le proprietà del controller come `body`, `query` e `ip` leggono da esso.

### controller.json(obj, [headers], [beautify], [replacer])

Type: `method`

Risponde con un oggetto serializzato come JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | Il valore da serializzare. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `beautify` | `Boolean` | no | `false` | Formatta il JSON con l'indentazione. |
| `replacer` | `Function` | no |  | Un replacer per `JSON.stringify()`. |

Returns: `Controller` Il controller.

Il content type è `application/json` e lo stato è `controller.status` oppure `200`. Un `ErrorBuilder` viene restituito come i suoi errori con il proprio stato. `beautify` può essere il secondo argomento.

Example: Un oggetto
```js
exports.install = function() {
	ROUTE('GET /api/products/', products);
};

function products() {
	this.json([{ id: 1, name: 'Book' }]);
}
```

Example: Formattato
```js
this.json({ name: 'Peter' }, true);
```

### controller.jsonstring(str, [headers])

Type: `method` · Since: `0.0.57`

Risponde con un testo che è già JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String` | yes |  | Il testo JSON. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

Usalo quando hai il JSON come stringa, per esempio da una cache. Il testo viene inviato così com'è, con il content type `application/json`.

Example: Da una cache
```js
function list() {
	this.jsonstring('[{"id":1}]');
}
```

### controller.plain(body, [headers])

Type: `method`

Risponde con testo semplice.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String|Object` | yes |  | Il testo. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

Il content type è `text/plain`. Un oggetto viene serializzato come JSON formattato; `null` dà un corpo vuoto.

Example: Testo
```js
function home() {
	this.plain('Hello world');
}
```

### controller.html(body, [headers])

Type: `method`

Risponde con HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String` | yes |  | L'HTML. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

Equivale a `content(body, 'text/html', headers)`.

Example: HTML
```js
function home() {
	this.html('<h1>Hello</h1>');
}
```

### controller.content(body, type, [headers])

Type: `method`

Risponde con un testo e il tuo content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String` | yes |  | Il contenuto. |
| `type` | `String` | no | `text/plain` | Il content type. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

Un `ErrorBuilder` come `body` viene restituito come JSON con il proprio stato.

Example: XML
```js
function feed() {
	this.content('<rss></rss>', 'application/xml');
}
```

### controller.view([name], [model], [headers], [partial])

Type: `method`

Renderizza una vista e risponde con essa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Il nome della vista senza `.html`. |
| `model` | `Object` | no |  | Il modello, disponibile nella vista come `model`. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `partial` | `Boolean` | no | `false` | Restituisce l'HTML come stringa e non risponde. Può essere il terzo argomento. |

Returns: `Controller|String` Il controller, oppure l'HTML quando `partial` è `true`.

La vista è un file `name.html` in `views/`, renderizzato dentro il layout (`layout` per impostazione predefinita, vedi `controller.layout()`). Le route di un controller diverso da `default` cercano le viste in `views/<controller name>/`. Il primo carattere del nome cambia il punto in cui viene cercato il file:

| Prefisso | Dove |
| --- | --- |
| `~` | La radice di `views/` |
| `#plugin/view` | Le viste di un plugin |
| `=theme/view` | Le viste di un tema |
| `@` | Un pacchetto |

Senza nome, la vista ha il nome dell'ultima parte dell'URL (`index` per `/`). Con `partial` impostato a `true` il metodo restituisce l'HTML renderizzato invece di rispondere.

Example: Una pagina
```js
exports.install = function() {
	ROUTE('GET /', home);
};

function home() {
	this.view('index', { title: 'Home' });
}
```

Example: HTML come stringa
```js
var html = this.view('~mail/order', order, true);
```

### controller.layout(name)

Type: `method`

Sceglie il layout per la vista successiva.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome della vista di layout, oppure una stringa vuota. |

Returns: `Controller` Il controller.

Il layout predefinito è `layout` (la configurazione `default_layout`). Una stringa vuota renderizza la vista senza layout.

Example: Senza layout
```js
function widget() {
	this.layout('');
	this.view('widget');
}
```

### controller.title(value)

Type: `method`

Imposta il titolo della pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Il titolo. |

Returns: `Controller` Il controller.

Il layout lo stampa con `@{title}`. Il testo viene codificato in HTML.

Example: Titolo
```js
this.title('Products');
this.view('products');
```

### controller.meta(title, [description], [keywords], [image])

Type: `method`

Imposta i valori meta della pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `title` | `String` | yes |  | Il titolo. |
| `description` | `String` | no |  | La descrizione. |
| `keywords` | `String|Array` | no |  | Le parole chiave. |
| `image` | `String` | no |  | L'URL di un'immagine. |

Returns: `Controller` Il controller.

Il layout li stampa con `@{meta}`. `keywords` può essere un array.

Example: Meta tag
```js
this.meta('Products', 'All our products', ['shop', 'books']);
this.view('products');
```

### controller.file(filename, [download], [headers], [callback])

Type: `method`

Risponde con un file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | Il file in `public/`, oppure `~` e un percorso assoluto. |
| `download` | `String|Boolean` | no |  | Un nome per il file scaricato; `true` usa il nome del file. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `callback` | `Function` | no |  | Viene eseguita quando il file è stato inviato. |

Returns: `Controller` Il controller.

Il file viene letto da `public/`. Un nome che inizia con `~` è un percorso assoluto.

Example: Download
```js
function invoice() {
	this.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');
}
```

### controller.binary(buffer, type, [encoding], [download], [headers])

Type: `method`

Risponde con un buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | I dati. |
| `type` | `String` | yes |  | Il content type. |
| `encoding` | `String` | no |  | Una conversione dei dati. |
| `download` | `String` | no |  | Un nome per il file scaricato. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

`encoding` converte il buffer prima dell'invio (`binary`, `utf8`, `ascii`).

Example: Un'immagine in memoria
```js
function pixel() {
	var buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');
	this.binary(buffer, 'image/gif');
}
```

### controller.stream(stream, type, [download], [headers], [callback], [nocompress])

Type: `method`

Risponde con uno stream leggibile.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream` | yes |  | Uno stream leggibile. |
| `type` | `String` | yes |  | Il content type. |
| `download` | `String` | no |  | Un nome per il file scaricato. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `callback` | `Function` | no |  | Viene eseguita quando lo stream è stato inviato. |
| `nocompress` | `Boolean` | no | `false` | Disattiva la compressione. |

Returns: `Controller` Il controller.

La risposta viene compressa a meno che `nocompress` sia `true`. I primi due argomenti possono essere scambiati (`type`, `stream`).

Example: Un file CSV
```js
function exportcsv() {
	var stream = Fs.createReadStream(PATH.databases('export.csv'));
	this.stream(stream, 'text/csv', 'export.csv');
}
```

### controller.redirect(url, [permanent])

Type: `method`

Reindirizza il client a un altro URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL di destinazione. |
| `permanent` | `Boolean` | no | `false` | Invia `301 Moved Permanently`. |

Returns: `Controller` Il controller.

Lo stato è `302`, oppure `301` quando `permanent` è `true`.

Example: Dopo un form
```js
function save() {
	this.redirect('/thanks/');
}
```

### controller.empty([headers])

Type: `method`

Risponde con un corpo vuoto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `headers` | `Object|Number` | no |  | Header aggiuntivi, oppure un codice di stato. |

Returns: `Controller` Il controller.

Un numero al posto degli header imposta il codice di stato. Per `204 No Content` puoi usare anche `controller.nocontent([headers])`.

Example: Accettato
```js
this.empty(202);
```

### controller.success([success], [value])

Type: `method`

Risponde con il JSON `{ "success": true }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | Il valore di `success`. |
| `value` | `Object` | no |  | Un valore aggiunto come `value`. |

Returns: `Controller` Il controller.

`success(value)` risponde `{ "success": true, "value": value }`. `success(false)` risponde `{ "success": false }`.

Example: Con un valore
```js
function create() {
	var id = UID();
	this.success(true, id);
	// {"success":true,"value":"..."}
}
```

### controller.invalid([status], [error])

Type: `method`

Risponde con un errore come JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `status` | `Number|String|Error|ErrorBuilder` | no |  | Un codice di stato, il nome dell'errore o l'errore. |
| `error` | `String` | no |  | Il testo dell'errore. |

Returns: `ErrorBuilder` Il builder con gli errori.

Gli errori vengono restituiti come array JSON con lo stato `400` (la configurazione `default_errorbuilder_status`). Un numero come primo argomento imposta lo stato; un `Error` o un `ErrorBuilder` viene restituito così com'è. La risposta viene inviata al tick successivo, quindi puoi ancora aggiungere errori al builder restituito.

Example: Validazione
```js
function save() {
	if (!this.body.email)
		return this.invalid('email', 'The email is required');
	this.success();
}
```

Example: Un altro stato
```js
this.invalid(409, 'The user exists');
```

### controller.done([value])

Type: `method`

Crea una callback che risponde con un successo o con un errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean|Object` | no |  | `true` aggiunge la risposta come `value`; un altro valore viene aggiunto esso stesso come `value`. |

Returns: `Function` Una callback `(err, response)`.

La callback ha la forma `(err, response)`. In caso di errore chiama `controller.invalid(err)`. Altrimenti risponde `{ "success": true }`; con `done(true)` la risposta viene aggiunta come `value`, e con un altro valore viene aggiunto quel valore.

Example: Qualsiasi callback (err, response)
```js
function remove(id) {
	// removeproduct(id, callback) is your own function
	removeproduct(id, this.done());
}

function create() {
	// answers { "success": true, "value": response }
	createproduct(this.body, this.done(true));
}
```

### controller.callback([view])

Type: `method`

Crea una callback che risponde con la risposta come JSON o con una vista.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `view` | `String` | no |  | Il nome di una vista. |

Returns: `Function` Una callback `(err, data)`.

La callback ha la forma `(err, data)`. Quando `err` è un `ErrorBuilder` e non hai passato una vista, i suoi errori vengono restituiti come JSON. Qualsiasi altro errore risponde con la pagina di errore `404`, oppure `500` quando l'`ErrorBuilder` contiene un `Error`. Senza errori risponde con `data` come JSON, oppure renderizza la vista con `data` come modello.

Example: JSON
```js
function list() {
	// loadproducts(callback) is your own function
	loadproducts(this.callback());
}
```

Example: Una vista
```js
function list() {
	loadproducts(this.callback('products'));
}
```

### controller.throw404([problem])

Type: `method`

Risponde con la pagina di errore 404 Not Found.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema, disponibile nella route di errore come `controller.exception`. |

Returns: `Controller` Il controller.

Esegue la route `#404` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. La stessa famiglia risponde ad altri stati: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` e `throw503()`. Ognuno ha un alias chiamato `view400()` … `view503()`. Non succede nulla quando la richiesta ha già ricevuto risposta.

Example: Record mancante
```js
function detail(id) {
	var self = this;
	// findproduct(id, callback) is your own function
	findproduct(id, function(err, item) {
		if (item)
			self.view('detail', item);
		else
			self.throw404();
	});
}
```

Example: La tua pagina
```js
exports.install = function() {
	ROUTE('#404', notfound);
};

function notfound() {
	this.status = 404;
	this.view('404');
}
```

### controller.throw403([problem])

Type: `method`

Risponde con la pagina di errore 403 Forbidden.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema, disponibile nella route di errore come `controller.exception`. |

Returns: `Controller` Il controller.

Esegue la route `#403` quando ne hai dichiarata una. Alias: `view403()`.

Example: Solo per gli amministratori
```js
function admin() {
	if (!this.user.admin)
		return this.throw403();
	this.view('admin');
}
```

### controller.throw500([error])

Type: `method`

Registra un errore nel log e risponde con la pagina di errore 500.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error|String` | no |  | L'errore. |

Returns: `Controller` Il controller.

L'errore viene registrato dal framework (`DEF.onError`). Poi viene eseguita la route `#500` quando ne hai dichiarata una. Alias: `view500()`.

Example: In una promise
```js
async function stats() {
	try {
		this.json(await loadstats());
	} catch (err) {
		this.throw500(err);
	}
}
```

### controller.cookie(name, [value], [expires], [options])

Type: `method`

Legge un cookie della richiesta o scrive un cookie nella risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del cookie. |
| `value` | `String` | no |  | Il valore da scrivere. |
| `expires` | `String` | no |  | Quando scade il cookie, per esempio `'7 days'`. |
| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |

Returns: `String|Controller` Il valore in lettura, il controller in scrittura.

Con un solo argomento restituisce il valore del cookie, oppure una stringa vuota. Con un valore aggiunge un header `Set-Cookie`. `expires` è un testo come `'5 days'` o `'2 hours'`; uno negativo (`'-1 day'`) rimuove il cookie. Al posto di `expires` puoi passare l'oggetto delle opzioni con `expires` al suo interno.

Opzioni: `domain`, `path` (predefinito `/`), `secure` (predefinito la configurazione `default_cookies_secure`), `httponly` e `samesite` (`Lax`, `Strict` o `None`; predefinito `Lax`, la configurazione `default_cookies_samesite`).

Example: Scrivere e leggere
```js
function login() {
	this.cookie('session', 'token', '7 days', { httponly: true });
	this.redirect('/');
}

function home() {
	var session = this.cookie('session');
	this.plain(session);
}
```

Example: Rimuovere
```js
this.cookie('session', '', '-1 day');
```

### controller.header(name, value)

Type: `method`

Imposta un header della risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'header. |
| `value` | `String` | yes |  | Il valore. |

Returns: `Controller` Il controller.

Example: Un header
```js
this.header('X-Total', '42');
this.json(items);
```

### controller.nocache()

Type: `method`

Disattiva la cache HTTP della risposta.

Returns: `Controller` Il controller.

Example: Dati aggiornati
```js
function stats() {
	this.nocache();
	this.json(getstats());
}
```

### controller.csrf()

Type: `method` · Since: `0.0.37`

Crea un token CSRF per la richiesta corrente.

Returns: `String` Il token.

Le route con il flag `csrf` verificano il token dall'header `x-csrf-token` o dall'argomento `?csrf=` dell'URL. Nelle viste lo stesso token è `@{csrf}`.

Example: Inviare il token
```js
exports.install = function() {
	ROUTE('GET /api/token/', token);
	ROUTE('POST /api/save/ csrf', save);
};

function token() {
	this.json({ token: this.csrf() });
}
```

### controller.autoclear([enable])

Type: `method`

Conserva o rimuove i file caricati quando la richiesta termina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` conserva i file. |

Returns: `Controller` Il controller.

`autoclear(false)` conserva i file temporanei di `controller.files` dopo la risposta, per un lavoro che prosegue in seguito. `controller.clear()` li rimuove immediatamente.

Example: Elaborare in seguito
```js
function upload() {
	this.autoclear(false);
	var file = this.files[0];
	this.success();
	// file.path stays on the disk: process it, then remove it
}
```

### controller.sse(data, [eventname], [id], [retry])

Type: `method`

Invia un server-sent event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `String|Object` | yes |  | I dati dell'evento. |
| `eventname` | `String` | no |  | Il nome dell'evento. |
| `id` | `String` | no |  | L'ID dell'evento. |
| `retry` | `Number` | no |  | Quanto attende il browser prima di riconnettersi, in millisecondi. |

Returns: `Boolean` `false` quando l'evento non può essere inviato (il client si è disconnesso o la richiesta ha già ricevuto risposta).

La prima chiamata risponde con gli header di `text/event-stream` e mantiene aperta la connessione. Un oggetto viene serializzato come JSON. Quando manca `retry`, la prima chiamata usa il timeout della route. L'ID dell'evento precedente inviato dal browser si trova in `controller.sseID`. Lo stream termina con `controller.close()`.

Example: Un orologio
```js
exports.install = function() {
	ROUTE('GET /clock/', clock, ['delay']);
};

function clock() {
	var self = this;
	var timer = setInterval(function() {
		if (!self.sse({ time: new Date() }))
			clearInterval(timer);
	}, 1000);
}
```

### controller.proxy(options)

Type: `method`

Inoltra la richiesta a un altro URL e risponde con la sua risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object|String` | yes |  | L'URL di destinazione, oppure le opzioni. |

Returns: `undefined` Niente.

Il metodo, il corpo, la query string e gli header della richiesta vengono inviati alla destinazione (tranne `host`, `connection`, `accept-encoding` e gli header `x-forwarded-*`). Lo stato e il corpo della risposta vengono restituiti al client. In caso di errore chiama `controller.invalid(err)`.

Opzioni: `url` (obbligatorio), `method`, `headers`, `timeout` (predefinito `10000` ms) e `callback(err, response)`, che viene eseguita prima della risposta.

Example: Inoltrare un'API
```js
exports.install = function() {
	ROUTE('GET /api/weather/', weather);
};

function weather() {
	this.proxy('https://api.example.com/weather');
}
```

### controller.baa([label])

Type: `method`

Legge l'autenticazione Basic, oppure la chiede al browser.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `label` | `String` | no |  | Il realm mostrato dal browser. |

Returns: `Object|null` Le credenziali senza etichetta; `null` con un'etichetta.

Senza argomento restituisce `{ user, password, empty }` dall'header `Authorization`. Con un'etichetta risponde `401` con l'header `WWW-Authenticate`, così il browser mostra una finestra di login.

Example: Una pagina protetta
```js
function admin() {
	var auth = this.baa();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.baa('Administration');
		return;
	}
	this.view('admin');
}
```

### controller.isConnected

Type: `property`

Indica se il client è ancora connesso.

Returns: `Boolean`

È `false` dopo che il client ha chiuso la connessione o dopo `controller.close()`. Controllalo nei lavori lunghi prima di rispondere.

Example: Lavoro lungo
```js
function report() {
	var self = this;
	// longtask(callback) is your own function
	longtask(function(err, data) {
		if (self.isConnected)
			self.json(data);
	});
}
```

### controller.isController

Type: `property`

Sempre `true` per un controller.

Returns: `Boolean`

Utile per distinguere un controller da un oggetto `$` in una funzione condivisa.

Example: Una funzione condivisa
```js
function getuser(ctx) {
	return ctx.isController ? ctx.user : ctx.controller.user;
}
```

### controller.secured

Type: `property`

Indica se la richiesta è arrivata via HTTPS.

Returns: `Boolean`

È `true` quando il protocollo è `https:` (o `wss:`). Dietro un proxy dipende dall'URL che vede il framework. Equivale a `req.secured`.

Example: Forzare HTTPS
```js
function index() {
	if (!this.secured)
		return this.redirect('https://' + this.req.host + this.url);
	this.view('index');
}
```

### controller.referrer

Type: `property`

L'header `Referer` della richiesta.

Returns: `String`

Una stringa vuota quando l'header manca.

Example: Tornare indietro
```js
function back() {
	this.redirect(this.referrer || '/');
}
```

### controller.robot

Type: `property`

Indica se lo user agent sembra un bot.

Returns: `Boolean`

Cerca nell'header `User-Agent` parole come `bot`, `crawler` e `spider`.

Example: Esempio
```js
function index() {
	if (this.robot)
		return this.plain('Hello robot');
	this.view('index');
}
```

### controller.ua

Type: `property`

Lo user agent analizzato, come testo breve con il browser e il sistema.

Returns: `String`

Usa `req.useragent(true)` per ottenere un oggetto con il browser, il sistema operativo e il dispositivo. Equivale a `req.ua`.

Example: Esempio
```js
function index() {
	console.log(this.ua);
	this.view('index');
}
```

### controller.uri

Type: `property`

L'URL della richiesta già analizzato.

Returns: `Object`

Un oggetto di `url.parse()` con `pathname`, `query`, `hostname` e le altre parti.

Example: Esempio
```js
function index() {
	this.plain(this.uri.pathname + ' ' + (this.uri.query || ''));
}
```

### controller.split

Type: `property`

Le parti del percorso dell'URL.

Returns: `String[]`

`/products/shoes/` dà `['products', 'shoes']`.

Example: Esempio
```js
// GET /docs/{page}/
function docs() {
	this.plain(this.split.join(' > '));
}
```

### controller.subdomain

Type: `property`

Il sottodominio della richiesta come array.

Returns: `String[]`

`shop.eu.example.com` dà `['shop', 'eu']`; `www` viene ignorato. È `null` senza sottodominio.

Example: Esempio
```js
function index() {
	var tenant = this.subdomain ? this.subdomain[0] : 'default';
	this.view('index', { tenant: tenant });
}
```

### controller.sessionid

Type: `property`

L'id della sessione della richiesta.

Returns: `String`

Impostato dal tuo delegato `AUTH()` o dal meccanismo delle sessioni. Equivale a `req.sessionid`.

Example: Esempio
```js
function logout() {
	// removesession(id) is your own function
	removesession(this.sessionid);
	this.redirect('/');
}
```

### controller.sseID

Type: `property`

L'id dell'ultimo evento ricevuto dal browser.

Returns: `String`

Il valore dell'header `Last-Event-ID` che il browser invia quando si riconnette a una route di server-sent events, oppure `null`.

Example: Esempio
```js
function events() {
	var last = this.sseID;
	this.sse({ resumed: !!last });
}
```

### controller.route

Type: `property`

La route a cui corrisponde la richiesta.

Returns: `Object`

Un oggetto interno del framework con l'URL, i flag, lo schema e le opzioni della route. Leggilo, non modificarlo.

Example: Esempio
```js
function index() {
	console.log(this.route.url);
	this.empty();
}
```

### controller.options

Type: `property`

Le opzioni personalizzate della route.

Returns: `Object`

L'oggetto che passi a `ROUTE()` come opzioni.

Example: Esempio
```js
exports.install = function() {
	ROUTE('GET /reports/', report, { title: 'Reports' });
};

function report() {
	this.plain(this.options.title);
}
```

### controller.flags

Type: `property`

I flag della route.

Returns: `String[]`

Un array con i flag della route, per esempio `['get', 'json']`.

Example: Esempio
```js
function index() {
	this.json(this.flags);
}
```

### controller.schema

Type: `property`

Il nome dello schema della route.

Returns: `String`

Per una route come `POST /api/users/ *Users --> save` è `'Users'`. Una stringa vuota quando la route non ha uno schema.

Example: Esempio
```js
function action() {
	console.log(this.schema);
	this.empty();
}
```

### controller.name

Type: `property`

Il nome del controller.

Returns: `String`

Il nome del file in `/controllers/` (senza `.js`) che ha dichiarato la route.

Example: Esempio
```js
function index() {
	this.plain(this.name);
}
```

### controller.breadcrumb

Type: `property`

Il breadcrumb dell'elemento corrente della sitemap.

Returns: `Object[]`

Gli elementi impostati da `controller.sitemap()`; nelle viste lo stesso elenco è in `@{sitemap}`.

Example: Esempio
```js
function detail() {
	this.sitemap('detail');
	this.json(this.breadcrumb);
}
```

### controller.jsonp(name, obj, [headers], [beautify], [replacer])

Type: `method`

Risponde con JSONP: una chiamata di una funzione JavaScript con i dati.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome della funzione JavaScript. |
| `obj` | `Object` | yes |  | I dati. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `beautify` | `Boolean` | no | `false` | Formatta il JSON. |
| `replacer` | `Function` | no |  | Un replacer per `JSON.stringify()`. |

Returns: `Controller` Il controller.

Il corpo è `name(json)` con il content type `application/x-javascript`. Senza `name` la funzione è `callback`. Un `ErrorBuilder` viene restituito come i suoi errori.

Example: Nome dalla query string
```js
function data() {
	this.jsonp(this.query.callback, { count: 10 });
}
```

### controller.throw400([problem])

Type: `method`

Risponde con la pagina di errore 400 Bad Request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Controller` Il controller.

Esegue la route `#400` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view400()`.

Example: Rispondere 400
```js
function action() {
	this.throw400('Bad Request');
}
```

### controller.throw401([problem])

Type: `method`

Risponde con la pagina di errore 401 Unauthorized.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Controller` Il controller.

Esegue la route `#401` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view401()`.

Example: Rispondere 401
```js
function action() {
	this.throw401('Unauthorized');
}
```

### controller.throw409([problem])

Type: `method`

Risponde con la pagina di errore 409 Conflict.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Controller` Il controller.

Esegue la route `#409` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view409()`.

Example: Rispondere 409
```js
function action() {
	this.throw409('Conflict');
}
```

### controller.throw501([problem])

Type: `method`

Risponde con la pagina di errore 501 Not Implemented.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Controller` Il controller.

Esegue la route `#501` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view501()`.

Example: Rispondere 501
```js
function action() {
	this.throw501('Not Implemented');
}
```

### controller.throw503([problem])

Type: `method`

Risponde con la pagina di errore 503 Service Unavailable.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Controller` Il controller.

Esegue la route `#503` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view503()`.

Example: Rispondere 503
```js
function action() {
	this.throw503('Service Unavailable');
}
```

### controller.view400([problem])

Type: `method`

Alias di `controller.throw400()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 400 nello stesso modo.

Example: Come throw400()
```js
function detail() {
	this.view400();
}
```

### controller.view401([problem])

Type: `method`

Alias di `controller.throw401()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 401 nello stesso modo.

Example: Come throw401()
```js
function detail() {
	this.view401();
}
```

### controller.view403([problem])

Type: `method`

Alias di `controller.throw403()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 403 nello stesso modo.

Example: Come throw403()
```js
function detail() {
	this.view403();
}
```

### controller.view404([problem])

Type: `method`

Alias di `controller.throw404()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 404 nello stesso modo.

Example: Come throw404()
```js
function detail() {
	this.view404();
}
```

### controller.view409([problem])

Type: `method`

Alias di `controller.throw409()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 409 nello stesso modo.

Example: Come throw409()
```js
function detail() {
	this.view409();
}
```

### controller.view500([error])

Type: `method`

Alias di `controller.throw500()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error` | no |  | L'errore, registrato nel log dal framework. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 500 nello stesso modo.

Example: Come throw500()
```js
function detail() {
	this.view500();
}
```

### controller.view501([problem])

Type: `method`

Alias di `controller.throw501()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 501 nello stesso modo.

Example: Come throw501()
```js
function detail() {
	this.view501();
}
```

### controller.view503([problem])

Type: `method`

Alias di `controller.throw503()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Il problema. |

Returns: `Controller` Il controller.

Risponde con la pagina di errore 503 nello stesso modo.

Example: Come throw503()
```js
function detail() {
	this.view503();
}
```

### controller.nocontent([headers])

Type: `method`

Risponde `204 No Content` senza corpo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Controller` Il controller.

Example: Niente da rispondere
```js
function ping() {
	this.nocontent();
}
```

### controller.destroy()

Type: `method`

Chiude la connessione senza rispondere.

Returns: `Controller` Il controller.

Il socket viene distrutto. Non succede nulla quando la richiesta ha già ricevuto risposta.

Example: Scartare una richiesta
```js
function upload() {
	if (this.req.headers['content-length'] > 1000000)
		return this.destroy();
	this.success();
}
```

### controller.close([end])

Type: `method`

Termina la risposta, soprattutto uno stream di server-sent events.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `end` | `Boolean` | no | `true` | Chiama `res.end()`. |

Returns: `Controller` Il controller.

Termina la risposta di `controller.sse()` e contrassegna il controller come disconnesso. Con `end` impostato a `false` la risposta viene solo contrassegnata come terminata.

Example: Fermare uno stream
```js
function events() {
	var self = this;
	self.sse({ step: 1 });
	setTimeout(function() {
		self.close();
	}, 5000);
}
```

### controller.cancel()

Type: `method`

Contrassegna il controller come annullato.

Returns: `Controller` Il controller.

Imposta `controller.isCanceled` a `true`. Chiamato in un handler di `ON('controller')`, impedisce l'esecuzione dell'azione della route, quindi l'handler deve rispondere da sé.

Example: Fermare le richieste durante la manutenzione
```js
ON('controller', function(controller) {
	if (CONF.maintenance) {
		controller.cancel();
		controller.throw503('Maintenance');
	}
});
```

### controller.clear()

Type: `method`

Rimuove subito i file caricati della richiesta.

Returns: `Controller` Il controller.

I file temporanei di `controller.files` vengono eliminati e `body`, `query` e i cookie della richiesta vengono svuotati.

Example: Dopo il lavoro
```js
function upload() {
	var self = this;
	var file = self.files[0];
	file.move(PATH.databases(file.filename), function() {
		self.clear();
		self.success();
	});
}
```

### controller.custom()

Type: `method`

Ti permette di rispondere tu stesso con la risposta di Node.js.

Returns: `Boolean` `true` quando puoi rispondere.

Il framework contrassegna la richiesta come già risposta e smette di attenderla. Poi scrivi su `controller.res` con `writeHead()` ed `end()`. Restituisce `false` quando la richiesta ha già ricevuto risposta.

Example: Scrivere la risposta
```js
function raw() {
	if (this.custom()) {
		this.res.writeHead(200, { 'Content-Type': 'text/plain' });
		this.res.end('OK');
	}
}
```

### controller.error(err)

Type: `method`

Registra nel log un errore con il nome del controller e l'URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error|String` | yes |  | L'errore. |

Returns: `Controller` Il controller.

L'errore va a `F.error()` e a `controller.exception`; alla richiesta non viene data risposta. Un `ErrorBuilder` invece viene restituito come JSON.

Example: Registrare e continuare
```js
function action() {
	this.error(new Error('Cache is empty'));
	this.json([]);
}
```

### controller.successful(callback)

Type: `method`

Crea una callback che risponde con l'errore e passa oltre solo il risultato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Viene eseguita in caso di successo con i risultati. |

Returns: `Function` Una callback `(err, a, b, c)`.

La funzione restituita ha la forma `(err, a, b, c)`. In caso di errore chiama `controller.invalid(err)`; altrimenti chiama `callback(a, b, c)` con il controller come `this`.

Example: Solo il percorso di successo
```js
function detail(id) {
	NOSQL('products').one().where('id', id).callback(this.successful(function(item) {
		this.view('detail', item);
	}));
}
```

### controller.hostname([path])

Type: `method`

Crea un URL assoluto con l'host della richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | Un percorso da aggiungere. |

Returns: `String` L'URL, per esempio `https://example.com/products/`.

Il protocollo, il nome host e la porta della richiesta, con `path` aggiunto.

Example: Un link per un'email
```js
function invite() {
	this.json({ url: this.hostname('/invite/' + UID() + '/') });
}
```

### controller.image(filename, make, [headers], [callback])

Type: `method`

Risponde con un'immagine modificata dall'elaboratore di immagini.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | L'immagine. |
| `make` | `Function` | yes |  | `function(image)`. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `callback` | `Function` | no |  | Viene eseguita quando la risposta termina. |

Returns: `Controller` Il controller.

`filename` è un file in `/public/` (oppure un percorso completo preceduto da `~`) o uno stream. `make(image)` modifica l'immagine con i metodi di `Image` (`resize()`, `quality()`, ...). Il risultato viene messo in cache in `/tmp/`. Richiede GraphicsMagick o ImageMagick.

Example: Una miniatura
```js
function thumbnail() {
	this.image('/img/photo.jpg', function(image) {
		image.resize(200, 200);
		image.quality(80);
	});
}
```

### controller.memorize(key, expire, [disabled], fn, [fnFrom])

Type: `method`

Mette in cache l'intera risposta di un'azione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | La chiave nella cache. |
| `expire` | `String|Date` | yes |  | Per quanto tempo, per esempio `'5 minutes'`. |
| `disabled` | `Boolean` | no | `false` | `true` salta la cache. |
| `fn` | `Function` | yes |  | Crea la risposta; viene eseguita con il controller come `this`. |
| `fnFrom` | `Function` | no |  | Viene eseguita prima di una risposta dalla cache. |

Returns: `Controller` Il controller.

La prima chiamata esegue `fn` e salva la risposta (una vista, JSON o testo) sotto `key` per `expire`. Le chiamate successive rispondono dalla cache, e prima viene eseguita `fnFrom`. Con `disabled` impostato a `true` la cache viene saltata. Il tema viene aggiunto alla chiave.

Example: Mettere in cache la home page
```js
function index() {
	this.memorize('home', '5 minutes', DEBUG, function() {
		this.view('index');
	});
}
```

### controller.description(value)

Type: `method`

Imposta la meta description della pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | La descrizione. |

Returns: `Controller` Il controller.

Nel layout viene scritta da `@{meta}`. `controller.keywords()` imposta le parole chiave e `controller.author()` l'autore nello stesso modo.

Example: Meta tag
```js
function index() {
	this.title('Shop');
	this.description('Shoes and clothes');
	this.view('index');
}
```

### controller.keywords(value)

Type: `method`

Imposta le meta keywords della pagina.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes |  | Le parole chiave. |

Returns: `Controller` Il controller.

Un array viene unito con virgole. Nel layout vengono scritte da `@{meta}`.

Example: Parole chiave
```js
function index() {
	this.keywords(['shoes', 'clothes']);
	this.view('index');
}
```

### controller.head([value], [...])

Type: `method`

Aggiunge tag nell'head del layout, oppure li legge.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | no |  | Il nome di un file o un tag HTML. |

Returns: `Controller|String` Il controller, oppure l'HTML senza argomenti.

Un file `.css` diventa un `<link>` e un file `.js` uno `<script>`; i nomi relativi puntano a `/public/css/` e `/public/js/`. Un valore che inizia con `<` viene aggiunto così com'è. Ogni valore viene aggiunto una sola volta. Senza argomenti restituisce l'HTML; nel layout usa `@{head}`.

Example: File per una pagina
```js
function editor() {
	this.head('editor.css', 'editor.js');
	this.view('editor');
}
```

### controller.place(name, [value], [...])

Type: `method`

Aggiunge contenuto in un punto con nome del layout, oppure lo legge.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del punto. |
| `value` | `String` | no |  | Il contenuto. |

Returns: `Controller|String` Il controller, oppure il contenuto con solo `name`.

Un valore `.js` diventa uno `<script>` e un valore `.css` un `<link>`; gli altri valori vengono aggiunti così come sono. Nel layout usa `@{place('name')}`.

Example: Script alla fine della pagina
```js
function index() {
	this.place('footer', '/js/chart.js');
	this.view('index');
}
```

### controller.theme(name)

Type: `method`

Imposta il tema delle viste di questa richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del tema. |

Returns: `Controller` Il controller.

Viste, layout e file statici vengono quindi cercati prima in `/themes/{name}/`. Il valore predefinito proviene da `CONF.default_theme`.

Example: Un tema per cliente
```js
function index() {
	this.theme(this.query.dark ? 'dark' : 'default');
	this.view('index');
}
```

### controller.component(name, [settings], [model])

Type: `method`

Renderizza un componente in HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del componente. |
| `settings` | `Object` | no |  | Le impostazioni del componente. |
| `model` | `Object` | no |  | Il modello; per impostazione predefinita il modello della vista. |

Returns: `String` L'HTML, oppure una stringa vuota per un componente sconosciuto.

Il componente è un file in `/components/`. Il suo CSS e il suo JS vengono aggiunti all'head del layout. Nelle viste usa `@{component('name')}`.

Example: HTML di un componente
```js
function widget() {
	this.html(this.component('chart', { color: 'red' }));
}
```

### controller.helper(name, [arg], [...])

Type: `method`

Esegue un helper di vista da `DEF.helpers`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'helper. |
| `arg` | `Object` | no |  | Argomenti per l'helper. |

Returns: `String` L'output dell'helper.

L'helper viene eseguito con il controller come `this`. Un helper sconosciuto restituisce una stringa vuota.

Example: Usare un helper in un'azione
```js
DEF.helpers.price = function(value) {
	return value.format(2) + ' EUR';
};

function price() {
	this.plain(this.helper('price', 10));
}
```

### controller.public(name, [path])

Type: `method`

Crea l'URL di un file in `/public/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |
| `path` | `String` | no |  | Un percorso unito a un URL relativo. |

Returns: `String` L'URL.

Rispetta le impostazioni degli URL statici e il tema. La famiglia `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` e `public_download()` fa lo stesso per la propria cartella.

Example: Un URL in JSON
```js
function config() {
	this.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });
}
```

### controller.public_js(name, [tag])

Type: `method`

Crea l'URL di un file nella cartella pubblica `js`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |
| `tag` | `Boolean` | no | `false` | Restituisce un tag HTML. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_script`, predefinito `/js/`). Con `tag` impostato a `true` restituisce il tag HTML (`<script>` o `<link>`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_js('app.js'));
}
```

### controller.public_css(name, [tag])

Type: `method`

Crea l'URL di un file nella cartella pubblica `css`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |
| `tag` | `Boolean` | no | `false` | Restituisce un tag HTML. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_style`, predefinito `/css/`). Con `tag` impostato a `true` restituisce il tag HTML (`<script>` o `<link>`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_css('app.css'));
}
```

### controller.public_image(name)

Type: `method`

Crea l'URL di un file nella cartella pubblica `img`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_image`, predefinito `/img/`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_image('logo.png'));
}
```

### controller.public_video(name)

Type: `method`

Crea l'URL di un file nella cartella pubblica `videos`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_video`, predefinito `/videos/`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_video('intro.mp4'));
}
```

### controller.public_font(name)

Type: `method`

Crea l'URL di un file nella cartella pubblica `fonts`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_font`, predefinito `/fonts/`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_font('icons.woff2'));
}
```

### controller.public_download(name)

Type: `method`

Crea l'URL di un file nella cartella pubblica `download`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il file. |

Returns: `String` L'URL.

La cartella proviene dalla configurazione (`static_url_download`, predefinito `/download/`).

Example: URL di un file
```js
function index() {
	this.plain(this.public_download('manual.pdf'));
}
```

### controller.runtest(url, [name], [callback])

Type: `method`

Aggiunge un test di una route ai test del framework.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | La route da testare. |
| `name` | `String` | no |  | Il nome del test. |
| `callback` | `Function` | no |  | `function(result)` che restituisce `true` in caso di successo. |

Returns: `Object` Il test.

I test di un controller vengono eseguiti uno dopo l'altro. `url` è una route come `'GET /api/products/'` o `'API /api/ products_query'` (in quel caso il nome del test è l'operazione). `callback(result)` riceve `{ err, value, response, name }` e restituisce `true` quando il test passa; senza di essa, un test passa quando non c'è errore.

Example: Testare le route da una route
```js
function selftest() {
	this.runtest('GET /api/products/', function(result) {
		return !result.err && result.value instanceof Array;
	});
	this.success();
}
```

### req.host

Type: `property`

L'header `Host` della richiesta.

Returns: `String`

Il nome host con la porta, per esempio `example.com:8000`.

Example: Esempio
```js
function index() {
	this.plain(this.req.host);
}
```

### req.secured

Type: `property`

Indica se la richiesta è arrivata via HTTPS.

Returns: `Boolean`

È `true` quando il protocollo è `https:` o `wss:`.

Example: Esempio
```js
MIDDLEWARE('https', function($) {
	if ($.req.secured)
		$.next();
	else
		$.res.redirect('https://' + $.req.host + $.req.url);
});
```

### req.isAuthorized

Type: `property`

Il risultato dell'autorizzazione.

Returns: `Boolean`

È `true` finché il tuo delegato `AUTH()` non viene eseguito; poi è `true` quando il delegato ha accettato l'utente e `false` quando lo ha rifiutato.

Example: Esempio
```js
function index() {
	this.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');
}
```

### req.isStaticFile

Type: `property`

Indica se la richiesta chiede un file statico.

Returns: `Boolean`

È `true` quando l'URL ha un'estensione di file e i file statici sono consentiti. Utile in `DEF.onLocale` e nei middleware.

Example: Esempio
```js
DEF.onLocale = function(req) {
	return req.isStaticFile ? '' : (req.query.lang || 'en');
};
```

### req.xhr

Type: `property`

Indica se la richiesta è arrivata da JavaScript.

Returns: `Boolean`

È `true` quando l'header `X-Requested-With` è `XMLHttpRequest`.

Example: Esempio
```js
function index() {
	if (this.req.xhr)
		this.json({ ok: true });
	else
		this.view('index');
}
```

### req.ip

Type: `property`

L'indirizzo IP del client.

Returns: `String`

Dietro un proxy è il primo indirizzo di `X-Forwarded-For`. Può essere impostato.

Example: Esempio
```js
function index() {
	this.plain(this.req.ip);
}
```

### req.uri

Type: `property`

L'URL della richiesta già analizzato.

Returns: `Object`

Un oggetto di `url.parse()` con `pathname`, `query`, `hostname` e `port`.

Example: Esempio
```js
function index() {
	this.plain(this.req.uri.pathname);
}
```

### req.path

Type: `property`

Le parti del percorso in minuscolo.

Returns: `String[]`

`/Products/Shoes/` dà `['products', 'shoes']`. `req.split` mantiene le maiuscole e minuscole originali.

Example: Esempio
```js
function index() {
	this.json(this.req.path);
}
```

### req.split

Type: `property`

Le parti del percorso dell'URL.

Returns: `String[]`

Le parti così come erano nell'URL. Equivale a `controller.split`.

Example: Esempio
```js
function index() {
	this.json(this.req.split);
}
```

### req.subdomain

Type: `property`

Il sottodominio come array, oppure `null`.

Returns: `String[]`

`www` viene ignorato. `a.localhost` dà `['a']`.

Example: Esempio
```js
function index() {
	this.json(this.req.subdomain);
}
```

### req.mobile

Type: `property`

Indica se lo user agent è un dispositivo mobile.

Returns: `Boolean`

Verifica l'header `User-Agent`. Può essere impostato.

Example: Esempio
```js
function index() {
	this.view(this.req.mobile ? 'mobile' : 'index');
}
```

### req.robot

Type: `property`

Indica se lo user agent sembra un bot.

Returns: `Boolean`

Verifica l'header `User-Agent`.

Example: Esempio
```js
function index() {
	this.plain(this.req.robot ? 'bot' : 'human');
}
```

### req.ua

Type: `property`

Lo user agent analizzato, come testo breve con il browser e il sistema.

Returns: `String`

Equivale a `req.useragent()`.

Example: Esempio
```js
function index() {
	this.plain(this.req.ua);
}
```

### req.query

Type: `property`

La query string come oggetto.

Returns: `Object`

Viene analizzata alla prima lettura e può essere impostata.

Example: Esempio
```js
function index() {
	this.json(this.req.query);
}
```

### req.body

Type: `property`

Il corpo della richiesta già analizzato.

Returns: `Object`

Un corpo JSON o di un form. Equivale a `controller.body`.

Example: Esempio
```js
function save() {
	this.json(this.req.body);
}
```

### req.files

Type: `property`

I file caricati.

Returns: `HttpFile[]`

Un array di oggetti `HttpFile` per le route con il flag `upload`. Equivale a `controller.files`.

Example: Esempio
```js
function upload() {
	this.json(this.req.files.map(function(file) {
		return file.filename;
	}));
}
```

### req.user

Type: `property`

L'utente accettato dal delegato `AUTH()`, oppure `null`.

Returns: `Object`

Equivale a `controller.user`.

Example: Esempio
```js
function index() {
	this.json(this.req.user);
}
```

### req.session

Type: `property`

L'oggetto sessione della richiesta, oppure `null`.

Returns: `Object`

Impostato dal tuo delegato `AUTH()` o dal meccanismo delle sessioni. Equivale a `controller.session`.

Example: Esempio
```js
function index() {
	this.json(this.req.session);
}
```

### req.useragent([structured])

Type: `method`

Analizza l'header `User-Agent`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `structured` | `Boolean` | no | `false` | Restituisce un oggetto. |

Returns: `String|Object` Lo user agent.

Senza argomento restituisce un testo breve con i nomi trovati nell'header, come il browser e il sistema. Con `true` restituisce `{ os, browser, device }`, dove `device` è `desktop`, `mobile`, `tablet` o `tv`. Il risultato viene messo in cache sulla richiesta.

Example: Dettagli del dispositivo
```js
function index() {
	this.json(this.req.useragent(true));
}
```

### req.cookie(name)

Type: `method`

Legge un cookie della richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del cookie. |

Returns: `String` Il valore.

Il valore viene decodificato. Un cookie mancante dà una stringa vuota. `controller.cookie(name)` fa lo stesso.

Example: Leggere un cookie in un middleware
```js
MIDDLEWARE('lang', function($) {
	$.req.$language = $.req.cookie('lang') || 'en';
	$.next();
});
```

### req.authorization()

Type: `method`

Legge l'header di autorizzazione Basic.

Returns: `Object` `{ user, password, empty }`.

Decodifica `Authorization: Basic ...` in `{ user, password, empty }`. `empty` è `true` quando manca l'utente o la password.

Example: Autenticazione Basic
```js
function admin() {
	var auth = this.req.authorization();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.header('WWW-Authenticate', 'Basic realm="Admin"');
		return this.throw401();
	}
	this.view('admin');
}
```

### req.authorize(callback)

Type: `method`

Esegue manualmente il delegato `AUTH()` per questa richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |

Returns: `Request` La richiesta.

`callback(err, user, isAuthorized)` riceve il risultato del delegato. Senza delegato `isAuthorized` è `false`. Utile per le route che non usano i flag di autorizzazione.

Example: Verificare un utente su una route pubblica
```js
function index() {
	var self = this;
	self.req.authorize(function(err, user, isAuthorized) {
		self.view('index', { user: isAuthorized ? user : null });
	});
}
```

### req.clear()

Type: `method`

Rimuove i file caricati della richiesta.

Returns: `Request` La richiesta.

Equivale a `controller.clear()`.

Example: Svuotare i file
```js
function upload() {
	this.req.clear();
	this.success();
}
```

### req.csrf()

Type: `method` · Since: `0.0.37`

Crea un token CSRF per la richiesta.

Returns: `String` Il token.

Equivale a `controller.csrf()`; usa `DEF.onCSRFcreate(req)`.

Example: Un token in un middleware
```js
MIDDLEWARE('token', function($) {
	$.res.setHeader('X-CSRF-Token', $.req.csrf());
	$.next();
});
```

### req.encrypt([enable])

Type: `method`

Cifra la risposta testuale di questa richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` la disattiva. |

Returns: `Request` La richiesta.

La risposta viene cifrata con `CONF.secret_encryption` e riceve l'header `X-Encryption: a`. `controller.encrypt([enable])` fa lo stesso.

Example: Cifrare una risposta
```js
function secret() {
	this.req.encrypt();
	this.json({ token: UID() });
}
```

### req.hostname([path])

Type: `method`

Crea un URL assoluto con l'host della richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | Un percorso da aggiungere. |

Returns: `String` L'URL.

Il protocollo, il nome host e la porta della richiesta, con `path` aggiunto. Equivale a `controller.hostname()`.

Example: URL assoluto
```js
function index() {
	this.plain(this.req.hostname('/login/'));
}
```

### req.nocache()

Type: `method`

Disattiva la cache HTTP della risposta.

Returns: `Request` La richiesta.

Chiama `res.nocache()`.

Example: In un middleware
```js
MIDDLEWARE('nocache', function($) {
	$.req.nocache();
	$.next();
});
```

### res.controller

Type: `property`

Il controller della richiesta.

Returns: `Controller`

Impostato quando un controller gestisce la richiesta.

Example: Esempio
```js
MIDDLEWARE('log', function($) {
	console.log($.res.controller ? 'controller' : 'no controller');
	$.next();
});
```

### res.success

Type: `property`

Indica se la risposta è stata inviata.

Returns: `Boolean`

È `true` dopo che il framework ha risposto alla richiesta.

Example: Esempio
```js
function action() {
	var self = this;
	setTimeout(function() {
		if (!self.res.success)
			self.empty();
	}, 1000);
}
```

### res.nocompress

Type: `property`

Disattiva la compressione dell'HTML e dei file statici per questa risposta.

Returns: `Boolean`

Con `true` il framework non minifica l'HTML e i file statici che invia.

Example: Esempio
```js
MIDDLEWARE('raw', function($) {
	$.res.nocompress = true;
	$.next();
});
```

### res.json(obj)

Type: `method`

Risponde con un oggetto come JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | Il valore. |

Returns: `Response` La risposta.

Lo stato proviene dalle opzioni della risposta (`200` per impostazione predefinita).

Example: JSON da una route con (req, res)
```js
ROUTE('GET /api/ping/', function(req, res) {
	res.json({ ok: true });
});
```

### res.content(code, body, type, [compress], [headers])

Type: `method`

Risponde con un corpo e un content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | Lo stato HTTP. |
| `body` | `String` | yes |  | Il corpo. |
| `type` | `String` | yes |  | Il content type. |
| `compress` | `Boolean` | no |  | Compressione. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Response` La risposta.

I corpi oltre 4 kB vengono compressi con GZIP.

Example: Un CSV
```js
ROUTE('GET /export/', function(req, res) {
	res.content(200, 'id;name\n1;Peter', 'text/csv');
});
```

### res.send([code], body, [type])

Type: `method`

Risponde nello stile di Express.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `200` | Lo stato HTTP. |
| `body` | `String|Object|Number` | yes |  | Il corpo. |
| `type` | `String` | no |  | Il content type. |

Returns: `Response` La risposta.

Una stringa è `text/html`, un numero viene restituito come il testo di quello stato, un oggetto è JSON e un `ErrorBuilder` viene restituito come i suoi errori. È pensato per i middleware scritti per Express.

Example: Stile Express
```js
ROUTE('GET /hello/', function(req, res) {
	res.send('<b>Hello</b>');
});
```

### res.binary(buffer, type, [encoding], [download], [headers])

Type: `method`

Risponde con un buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | I dati. |
| `type` | `String` | yes |  | Il content type. |
| `encoding` | `String` | no |  | La codifica del buffer. |
| `download` | `String` | no |  | Un nome di file da scaricare. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |

Returns: `Response` La risposta.

`download` imposta il nome del file di `Content-Disposition`.

Example: Un file generato
```js
ROUTE('GET /file/', function(req, res) {
	res.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');
});
```

### res.image_nocache(input, make, [headers], [callback])

Type: `method`

Risponde con un'immagine modificata senza la cache di `/tmp/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `input` | `String|Stream` | yes |  | L'immagine. |
| `make` | `Function` | yes |  | `function(image)`. |
| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |
| `callback` | `Function` | no |  | Viene eseguita alla fine. |

Returns: `Response` La risposta.

Funziona come `res.image()`, ma il risultato viene creato per ogni richiesta.

Example: Immagine con un timestamp
```js
ROUTE('GET /stamp/', function(req, res) {
	res.image_nocache(PATH.public('img/photo.jpg'), function(image) {
		image.resize(300, 200);
	});
});
```

### res.nocache()

Type: `method`

Disattiva la cache HTTP della risposta.

Returns: `Response` La risposta.

Rimuove `If-None-Match` e `If-Modified-Since` dalla richiesta e imposta `Cache-Control: private, no-cache, no-store, max-age=0`.

Example: In una route con (req, res)
```js
ROUTE('GET /now/', function(req, res) {
	res.nocache();
	res.json({ now: new Date() });
});
```

### res.throw409([problem])

Type: `method`

Risponde con la pagina di errore 409 Conflict.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Response` La risposta.

Esegue la route `#409` quando ne hai dichiarata una.

Example: Rispondere 409
```js
ROUTE('GET /legacy/', function(req, res) {
	res.throw409();
});
```

### res.throw501([problem])

Type: `method`

Risponde con la pagina di errore 501 Not Implemented.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | Una descrizione del problema. |

Returns: `Response` La risposta.

Esegue la route `#501` quando ne hai dichiarata una.

Example: Rispondere 501
```js
ROUTE('GET /legacy/', function(req, res) {
	res.throw501();
});
```
