---
title: Controller
project: Total.js V5
version: 0.0.20
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/controller/
updated: 2026-11-18T16:57:24.576Z
---

# Controller

> Proprietà e metodi del controller `$` che ogni azione di una route riceve.

Il controller è l'argomento `$` di ogni azione di una route. Contiene i dati della richiesta (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) e i metodi che inviano la risposta (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Per una panoramica con esempi, leggi la guida [Controller](../../guides/controller/).

## API

### $.req

Type: `property`

L'oggetto request di Node.js.

Returns: `IncomingMessage`

L'`http.IncomingMessage` della richiesta. Usalo solo per ciò che il controller non offre.

### $.res

Type: `property`

L'oggetto response di Node.js.

Returns: `ServerResponse`

L'`http.ServerResponse` della richiesta. Quando ci scrivi tu, chiama prima `$.custom()` così il framework non risponde anch'esso alla richiesta.

### $.method

Type: `property`

Il metodo HTTP della richiesta.

Returns: `String`

Una stringa in maiuscolo come `GET`, `POST`, `PUT`, `PATCH` o `DELETE`.

Example: Esempio
```js
ROUTE('POST /api/items/', function($) {
	// $.method === 'POST'
	$.success();
});
```

### $.url

Type: `property`

Il percorso dell'URL.

Returns: `String`

Il percorso senza la query string. Un percorso senza estensione di file termina sempre con `/`, e gli slash doppi vengono uniti. Le lettere mantengono maiuscole e minuscole.

Example: Esempio
```js
ROUTE('GET /docs/', function($) {
	// /docs?page=1 gives '/docs/'
	$.plain($.url);
});
```

### $.uri

Type: `property`

L'URL analizzato.

Returns: `Object`

Un oggetto con `pathname` (uguale a `$.url`), `search` (la query string senza `?`), `split` (i segmenti), `ext` (l'estensione del file) e `file` (`true` per la richiesta di un file statico).

### $.split

Type: `property`

I segmenti del percorso.

Returns: `String[]`

Un array delle parti del percorso: `/blog/2025/hello/` dà `['blog', '2025', 'hello']`. Il percorso radice `/` dà un array vuoto.

Example: Esempio
```js
ROUTE('GET /blog/*', function($) {
	$.json($.split);
});
```

### $.params

Type: `property`

Le parti dinamiche dell'URL.

Returns: `Object`

Ogni `{name}` della route diventa una chiave con il segmento corrispondente del percorso come stringa. Converti tu numeri e date.

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

function order($) {
	var id = $.params.id;
	$.json({ id: id });
}
```

### $.query

Type: `property`

La query string come oggetto.

Returns: `Object`

I valori sono stringhe: `?page=2&q=shoes` dà `{ page: '2', q: 'shoes' }`. Puoi assegnare un nuovo oggetto. In una route API, contiene la query del campo `schema`.

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

### $.body

Type: `property`

Il corpo della richiesta già analizzato.

Returns: `Object`

Per le richieste `POST`, `PUT`, `PATCH` e `DELETE`. Un body JSON viene analizzato in un oggetto, un form URL-encoded in un oggetto di stringhe, e una richiesta `multipart/form-data` dà i campi del form. Gli altri content type mantengono `{}` e i dati grezzi sono in `$.payload`. In una route API, contiene i `data` della richiesta.

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

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

### $.payload

Type: `property`

Il body grezzo come Buffer.

Returns: `Buffer`

I byte del body per ogni content type tranne `multipart/form-data`. Usalo per XML, testo semplice o upload binari. Viene rilasciato quando la risposta termina.

Example: Esempio
```js
ROUTE('POST /api/xml/', function($) {
	var xml = $.payload.toString('utf8');
	$.plain('Received ' + xml.length + ' chars');
});
```

### $.files

Type: `property`

I file caricati.

Returns: `HttpFile[]`

Un array di file (`HttpFile`) di una richiesta `multipart/form-data`, vuoto per le altre richieste. I file sono temporanei e vengono rimossi quando la risposta termina, a meno che tu non li sposti o chiami `$.autoclear(false)`.

Example: Esempio
```js
function upload($) {
	var names = [];
	for (var file of $.files)
		names.push(file.filename + ' (' + file.size + ' bytes)');
	$.json(names);
}
```

### $.headers

Type: `property`

Gli header della richiesta.

Returns: `Object`

L'oggetto headers di Node.js: i nomi sono in minuscolo.

Example: Esempio
```js
function info($) {
	$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });
}
```

### $.ip

Type: `property`

L'indirizzo IP del client.

Returns: `String`

Il primo indirizzo di `X-Forwarded-For` quando l'header esiste (dietro un proxy), altrimenti l'indirizzo remoto della connessione.

Example: Esempio
```js
function track($) {
	console.log('Request from', $.ip);
	$.success();
}
```

### $.ua

Type: `property`

Un nome breve del client ricavato dall'header User-Agent.

Returns: `String`

Il sistema e il browser trovati in `User-Agent`, per esempio `Mac OS Chrome`, oppure una stringa vuota se l'header manca.

### $.mobile

Type: `property`

`true` per un dispositivo mobile.

Returns: `Boolean`

`true` quando `User-Agent` corrisponde a un telefono o a un tablet (Android, iPhone, iPad, Mobile, Tablet...).

### $.robot

Type: `property`

`true` per un crawler.

Returns: `Boolean`

`true` quando `User-Agent` contiene `search`, `agent`, `bot`, `crawler` o `spider`.

### $.xhr

Type: `property`

`true` per una XMLHttpRequest.

Returns: `Boolean`

`true` quando la richiesta ha l'header `X-Requested-With: XMLHttpRequest`. `$.fallback()` risponde a queste richieste con JSON invece che con una pagina HTML.

### $.protocol

Type: `property`

Il protocollo della richiesta.

Returns: `String`

`https` per una connessione cifrata o quando lo indica un proxy (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` o `X-Forwarded-Port: 443`), altrimenti `http`.

### $.address

Type: `property`

L'URL completo della richiesta.

Returns: `String`

Il protocollo, l'host e l'URL originale con la query string, per esempio `https://example.com/products/?page=2`.

### $.user

Type: `property`

L'utente autenticato.

Returns: `Object`

L'oggetto che il tuo delegate di autorizzazione ha restituito per la richiesta, oppure `undefined` quando nessuno ha effettuato l'accesso. Vedi [Autorizzazione](../../guides/authorization/).

Example: Esempio
```js
ROUTE('+GET /api/account/', function($) {
	$.json({ name: $.user.name });
});
```

### $.language

Type: `property`

La lingua della richiesta.

Returns: `String`

Il valore restituito dal tuo delegate di localizzazione, oppure una stringa vuota. Seleziona la traduzione delle viste e dei messaggi di errore. Vedi [Localizzazione](../../guides/localization/).

### $.response

Type: `property`

La risposta che verrà inviata.

Returns: `Object`

Un oggetto con `status` (predefinito `200`), `headers` (un oggetto di header della risposta), `cache` (cache HTTP per i file) e `minify`. Modificalo prima di chiamare un metodo di risposta.

Example: Stato e un header
```js
function create($) {
	$.response.status = 201;
	$.response.headers['x-version'] = '1';
	$.json({ id: UID() });
}
```

### $.json(value, [beautify], [replacer])

Type: `method`

Invia JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Il valore da serializzare. |
| `beautify` | `Boolean` | no | `false` | `true` indenta il JSON con tabulazioni. |
| `replacer` | `Function|Array` | no |  | Un replacer per `JSON.stringify()`. |

Serializza `value` con `JSON.stringify()`, imposta `content-type: application/json` e header che disattivano la cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indenta l'output con tabulazioni. `replacer` viene passato a `JSON.stringify()` come secondo argomento: una funzione `(key, value)` o un array di chiavi da mantenere.

Example: Esempio
```js
ROUTE('GET /api/products/', function($) {
	$.json([{ id: 1, name: 'Shoes' }]);
});
```

Example: Formattare e nascondere una chiave
```js
ROUTE('GET /api/debug/', function($) {
	$.json({ id: 1, password: 'secret' }, true, function(key, value) {
		return key === 'password' ? undefined : value;
	});
});
```

### $.jsonstring(value)

Type: `method`

Invia una stringa che è già JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | Una stringa JSON. |

Invia la stringa così com'è con gli stessi header di `$.json()`. Usalo per JSON che hai in cache o che hai letto da un file.

Example: Esempio
```js
function cached($) {
	$.jsonstring('{"ok":true}');
}
```

### $.success([value])

Type: `method`

Invia `{ success: true, value: value }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | Un valore opzionale per la chiave `value`. |

Una scorciatoia per la risposta tipica di un'API. Senza `value` la risposta è `{"success":true}`.

Example: Esempio
```js
function remove($) {
	NOSQL('products').remove().id($.params.id);
	$.success($.params.id);
}
```

### $.invalid(error)

Type: `method`

Invia un errore come JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `String|Error|ErrorBuilder|Number` | yes |  | L'errore. |

Accetta una stringa, un `Error`, un `ErrorBuilder` o un codice di stato HTTP. La risposta è un array JSON come `[{"error":"Name is required"}]` con lo stato `400`, oppure il codice di stato indicato (`$.invalid(404)` dà `[{"error":"404: Not Found"}]` con stato `404`). Il testo scritto come `@(text)` viene tradotto da una risorsa. Senza argomenti invia `401`. La risposta viene inviata in modo asincrono.

Example: Esempio
```js
function save($) {
	if (!$.body.email) {
		$.invalid('@(Email is required)');
		return;
	}
	$.success();
}
```

### $.invalidsafe(message, [error])

Type: `method`

Invia un messaggio di errore e registra l'errore reale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String|Number|ErrorBuilder` | yes |  | L'errore per il client. |
| `error` | `Error|String` | no |  | L'errore per il log. |

Invia `message` come fa `$.invalid(message)` e scrive `error` nel log degli errori con `F.error()` e l'URL della richiesta. Il client riceve solo il messaggio. `message` può essere anche un `ErrorBuilder`.

Example: Esempio
```js
function report($) {
	F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {
		if (err)
			$.invalidsafe('The report is not available', err);
		else
			$.content(buffer, 'text/csv');
	});
}
```

### $.html(value)

Type: `method`

Invia HTML.

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

Imposta `content-type: text/html` e invia la stringa. Viene minificata quando la chiave di configurazione `$minifyhtml` è `true` (il valore predefinito).

Example: Esempio
```js
ROUTE('GET /hello/', function($) {
	$.html('<h1>Hello</h1>');
});
```

### $.throw(error)

Type: `method`

Scrive un errore nel log.

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

Returns: `Controller` Lo stesso controller.

Passa `error` con l'URL della richiesta al gestore degli errori del framework (`DEF.onError`): viene stampato, conservato in `F.errors` ed emesso come evento `error`. Al client non viene inviato nulla. Restituisce `$`.

Example: Esempio
```js
function save($) {
	NOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {
		err && $.throw(err);
	});
	$.success();
}
```

### $.plain(value)

Type: `method`

Invia testo semplice.

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

Imposta `content-type: text/plain`. `$.text()` è lo stesso metodo.

Example: Esempio
```js
ROUTE('FILE /robots.txt', function($) {
	$.plain('User-agent: *');
});
```

### $.xml(value)

Type: `method`

Invia XML.

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

Imposta `content-type: text/xml` e invia la stringa.

Example: Esempio
```js
function feed($) {
	$.xml('<?xml version="1.0"?><rss></rss>');
}
```

### $.empty()

Type: `method`

Invia lo stato 204 senza body.

Usalo quando una richiesta non ha bisogno di dati nella risposta.

Example: Esempio
```js
ROUTE('POST /api/ping/', function($) {
	$.empty();
});
```

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

Type: `method`

Reindirizza il client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL di destinazione. |
| `permanent` | `Boolean` | no | `false` | `true` per un redirect permanente (301). |

Imposta l'header `Location` e lo stato `302`, oppure `301` quando `permanent` è `true`.

Example: Esempio
```js
ROUTE('GET /old/', function($) {
	$.redirect('/new/', true);
});
```

### $.view([name], [model])

Type: `method`

Renderizza una vista e la invia come HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Il nome della vista, senza estensione. |
| `model` | `Object` | no |  | Il model per la vista. |

Returns: `View` L'istanza della vista.

Renderizza la vista `name` della directory `/views/` con `model` e la invia con `$.html()`. Con il layout di `$.layout()`. Senza `name` restituisce solo una nuova istanza di `View` per il controller. Vedi [Viste](../../guides/views/).

Example: Esempio
```js
function detail($) {
	NOSQL('products').one().id($.params.id).callback(function(err, response) {
		if (response)
			$.view('detail', response);
		else
			$.fallback(404);
	});
}
```

### $.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. |

La vista renderizzata con `$.view()` viene inserita nel layout `name`.

Example: Esempio
```js
function admin($) {
	$.layout('layout-admin');
	$.view('dashboard');
}
```

### $.file(path, [download])

Type: `method`

Invia un file dal disco.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | Un percorso assoluto del file. |
| `download` | `Boolean|String` | no |  | Un nome di file per il download, oppure `true`. |

Imposta il content type dall'estensione e supporta le richieste `Range`, gzip e gli header di cache HTTP. I file JS, CSS e HTML vengono minificati a meno che il loro nome contenga `.min`, `-min` o `@min`. Con `download` il browser salva il file: passa `true` per mantenerne il nome o una stringa per rinominarlo. Un file mancante dà `404`.

Example: Esempio
```js
ROUTE('GET /download/', function($) {
	$.file(PATH.root('reports/2025.pdf'), 'report.pdf');
});
```

### $.stream(type, stream, [download])

Type: `method`

Invia uno stream leggibile.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | Il content type. |
| `stream` | `ReadableStream` | yes |  | Lo stream. |
| `download` | `String` | no |  | Un nome di file per il download. |

Invia `stream` alla risposta tramite pipe con il content type `type` (predefinito `application/octet-stream`). I tipi testuali vengono compressi con gzip quando il client lo supporta. Una stringa `download` invia lo stream come allegato con quel nome.

Example: Esempio
```js
function exportcsv($) {
	var stream = F.Fs.createReadStream(PATH.root('export.csv'));
	$.stream('text/csv', stream, 'export.csv');
}
```

### $.binary(buffer, type, [download])

Type: `method`

Invia un Buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | I dati. |
| `type` | `String` | yes |  | Il content type. |
| `download` | `String` | no |  | Un nome di file per il download. |

Invia i byte con il content type `type`. Una stringa `download` li invia come allegato con quel nome.

Example: Esempio
```js
function pixel($) {
	var buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
	$.binary(buffer, 'image/gif');
}
```

### $.content(value, [type])

Type: `method`

Invia una stringa o un Buffer con un content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | Il contenuto. |
| `type` | `String` | no | `'application/octet-stream'` | Il content type. |

Invia `value` con l'header `content-type: type`; senza `type` è `application/octet-stream`. Una stringa viene inviata come UTF-8. A differenza di `$.binary()`, accetta anche una stringa e non ha un nome di download.

Example: CSV
```js
ROUTE('GET /export/', function($) {
	$.content('id,name\n1,Mug\n', 'text/csv');
});
```

### $.image(opt)

Type: `method`

Elabora un'immagine e la invia.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | yes |  | Le opzioni. |

Carica uno stream di immagine, ti permette di modificarlo e invia il risultato. `opt.ext` (obbligatorio) è l'estensione dell'output, `opt.load(next, opt)` chiama `next(stream)` con la sorgente, `opt.image(img, opt)` modifica l'immagine (vedi [Immagini](../../guides/images/)), `opt.cache` è una chiave per conservare il risultato nella directory temporanea, e `opt.date` una data per la cache HTTP.

Example: Esempio
```js
function thumbnail($) {
	$.image({
		ext: 'jpg',
		cache: 'thumb_' + $.params.id,
		load: function(next) {
			next(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));
		},
		image: function(img) {
			img.resize(200, 200);
		}
	});
}
```

### $.filefs(name, id, [download], [checkmeta])

Type: `method`

Invia un file da un file storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del file storage. |
| `id` | `String` | yes |  | L'identificatore del file. |
| `download` | `Boolean|String` | no |  | Invia come allegato. |
| `checkmeta` | `Function` | no |  | Un controllo dei metadati. |

Returns: `Object` Le opzioni passate allo storage.

Invia il file `id` dal file storage `name` (vedi [File storage](../../guides/file-storage/)). `download` lo invia come allegato, `true` con il nome salvato o una stringa per un altro nome. `checkmeta` è una funzione che riceve i metadati del file e decide se può essere inviato.

Example: Esempio
```js
ROUTE('GET /files/{id}/', function($) {
	$.filefs('files', $.params.id);
});
```

### $.proxy(opt)

Type: `method`

Inoltra la richiesta a un altro server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `String|Object` | yes |  | L'URL di destinazione o le opzioni. |

Invia il metodo, gli header, il body e la query string della richiesta a `opt` (un URL, oppure un oggetto con `url`, `method`, `headers`, `timeout` (predefinito 10000 ms) e `callback(err, response)`) e risponde con la risposta di quel server.

Example: Esempio
```js
ROUTE('GET /api/weather/', function($) {
	$.proxy('https://weather.example.com/today/');
});
```

### $.fallback(code, [error])

Type: `method`

Invia una pagina di errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | Il codice di stato HTTP. |
| `error` | `String|Error` | no |  | L'errore per la modalità debug. |

Quando esiste una route `#code` (per esempio `ROUTE('#404', fn)`), la sua azione gestisce la richiesta; lo stato resta `200` a meno che l'azione non imposti `$.response.status`. Altrimenti invia la pagina di errore integrata con lo stato `code`, oppure `$.invalid(code)` per le richieste XHR. `error` viene mostrato nella pagina in modalità debug.

Example: Esempio
```js
exports.install = function() {
	ROUTE('GET /secret/', function($) {
		$.fallback(404);
	});
	ROUTE('#404', function($) {
		$.view('404');
	});
};
```

### $.callback([err], [value])

Type: `method`

Risponde da una callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | no |  | Un errore. |
| `value` | `Object` | no |  | Il valore da inviare. |

Returns: `Function` Una callback quando viene chiamato senza argomenti.

Senza argomenti restituisce una funzione `(err, response)` che chiama `$.invalid(err)` o `$.json(response)`. Con argomenti risponde subito: `$.invalid(err)`, `$.success()` quando `value` è `undefined`, oppure `$.json(value)`.

Example: Esempio
```js
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.callback());
});
```

### $.done([value])

Type: `method`

Restituisce una callback che risponde con successo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|Boolean` | no |  | Il valore, oppure `true` per la risposta della callback. |

Returns: `Function` Una callback.

La funzione restituita `(err, response)` chiama `$.invalid(err)` in caso di errore, altrimenti invia `{ success: true, value: value }`. Passa `true` per usare la `response` della callback come valore.

Example: Esempio
```js
ROUTE('POST /api/products/', function($) {
	NOSQL('products').insert($.body).callback($.done(true));
});
```

### $.successful(callback)

Type: `method`

Restituisce una callback che gestisce gli errori per te.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Chiamata quando non c'è errore. |

Returns: `Function` Una callback.

La funzione restituita `(err, a, b, c)` chiama `$.invalid(err)` in caso di errore, altrimenti `callback(a, b, c)` con il controller come `this`.

Example: Esempio
```js
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.successful(function(response) {
		$.json(response);
	}));
});
```

### $.custom()

Type: `method`

Indica al framework che invii tu la risposta.

Segna il controller come terminato, così nessun metodo di risposta ci scrive. Poi scrivi su `$.res` con l'API di Node.js.

Example: Esempio
```js
ROUTE('GET /events/', function($) {
	$.custom();
	$.res.writeHead(200, { 'content-type': 'text/event-stream' });
	$.res.write('data: hello\n\n');
});
```

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

Type: `method`

Legge o imposta un cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del cookie. |
| `value` | `String` | no |  | Il valore da impostare. |
| `expires` | `Date|String|Object` | no |  | La scadenza, oppure le opzioni. |
| `options` | `Object` | no |  | Le opzioni del cookie. |

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

Con il solo `name` restituisce il valore decodificato del cookie, oppure una stringa vuota. Con `value` aggiunge un header `Set-Cookie` (un cookie con lo stesso nome impostato prima nella richiesta viene sostituito) e restituisce il controller. `expires` è un `Date`, una stringa come `'7 days'`, oppure l'oggetto delle opzioni. Le opzioni sono `expires`, `domain`, `path` (predefinito `/`), `secure` (predefinito da `$cookiesecure`), `httponly` e `samesite` (predefinito da `$cookiesamesite`, `'Lax'`).

Example: Esempio
```js
function login($) {
	$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });
	$.success();
}

function profile($) {
	$.json({ session: $.cookie('session') });
}
```

### $.httpcache(date)

Type: `method`

Imposta gli header di cache HTTP.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Date|String` | yes |  | La data dell'ultima modifica. |

Imposta `Last-Modified` a `date`, `ETag`, e `Expires` e `Cache-Control` quando non sono ancora impostati.

Example: Esempio
```js
function article($) {
	var updated = new Date(2025, 0, 1);
	if ($.notmodified(updated.toUTCString()))
		return;
	$.httpcache(updated);
	$.view('article');
}
```

### $.notmodified(date)

Type: `method`

Risponde 304 quando il client ha la stessa versione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `String` | yes |  | La data dell'ultima modifica come stringa UTC. |

Returns: `Boolean` `true` quando la risposta 304 è stata inviata.

Confronta `date` (una stringa UTC) con l'header `If-Modified-Since`. Quando sono uguali invia `304 Not Modified` e restituisce `true`.

### $.hostname([path])

Type: `method`

Restituisce il protocollo e l'host.

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

Returns: `String` L'URL.

Dà `protocol://host` della richiesta con un percorso opzionale aggiunto in coda.

Example: Esempio
```js
function share($) {
	$.json({ url: $.hostname('/products/' + $.params.id + '/') });
}
```

### $.href([key], [value])

Type: `method`

Restituisce la query string con un parametro modificato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String|Object` | no |  | Il nome del parametro, o un oggetto con i parametri da impostare. |
| `value` | `String|Number|Array|Object` | no |  | Il nuovo valore. |

Returns: `String` La query string con `?`, o una stringa vuota.

Senza argomenti restituisce la query string della richiesta (`?page=2&sort=name`), oppure una stringa vuota. `$.href(key, value)` la restituisce con `key` impostato a `value`; gli altri parametri restano. Senza `value` viene mantenuto il valore attuale di `key`. Altri argomenti dopo `value` sono nomi di parametri da rimuovere. Un valore array scrive il parametro una volta per ogni elemento e un valore oggetto viene scritto come JSON. `$.href({ key: value, ... })` restituisce l'URL della richiesta con la query string modificata dalle chiavi dell'oggetto. Funziona come `@{href()}` nelle viste.

Example: Paginazione
```js
// GET /products/?page=2&sort=name
function products($) {
	$.json({
		next: $.href('page', 3),           // ?page=3&sort=name
		current: $.href()                  // ?page=2&sort=name
	});
}
```

Example: Rimuovere un parametro o modificarne diversi
```js
// GET /products/?page=2&sort=name&q=pen
$.href('page', 1, 'sort');           // ?page=1&q=pen
$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen
```

### $.touch([url])

Type: `method`

Cancella lo stato in cache di un file statico.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | `$.url` | L'URL del file. |

Returns: `Controller` Lo stesso controller.

Chiama `TOUCH(url)`; senza `url` usa l'URL della richiesta. Usalo dopo che la route ha modificato un file in `public/`. Restituisce `$`.

Example: Esempio
```js
ROUTE('POST /api/theme/', function($) {
	F.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {
		if (err) {
			$.invalidsafe('The theme can\'t be saved', err);
			return;
		}
		$.touch('/css/theme.css');
		$.success();
	});
});
```

### $.action(name, model)

Type: `method`

Esegue un'azione con questo controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'azione, ad esempio `Products/list`. |
| `model` | `Object` | yes |  | I dati per l'azione. |

Returns: `Object` L'istanza dell'azione.

Chiama l'azione `name` (vedi [Azioni](../../guides/actions/)) con `model` e il controller. Chiama `.autorespond()` sul risultato per rispondere alla richiesta con l'output dell'azione.

Example: Esempio
```js
ROUTE('POST /api/orders/', function($) {
	$.action('Orders/create', $.body).autorespond();
});
```

### $.authorize([callback])

Type: `method`

Esegue manualmente il delegate di autorizzazione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Riceve `(err, user)`. |

Returns: `Promise` Quando viene chiamato senza callback.

Chiama il tuo delegate di autorizzazione per questa richiesta. Quando restituisce un utente, `$.user` viene impostato. La callback è `(err, user)`; senza callback il metodo restituisce una `Promise` con l'utente (oppure `undefined`).

Example: Esempio
```js
ROUTE('GET /api/me/', async function($) {
	var user = await $.authorize();
	$.json({ signed: !!user });
});
```

### $.csrf()

Type: `method`

Crea un token CSRF.

Returns: `String` Il token.

Restituisce un token legato all'indirizzo IP e al browser del client, valido per il tempo indicato in `$csrfexpiration` (predefinito `30 minutes`). Richiede la chiave di configurazione `secret_csrf`; senza di essa il token è una stringa vuota.

Example: Esempio
```js
ROUTE('GET /form/', function($) {
	$.view('form', { token: $.csrf() });
});
```

### $.autoclear([value])

Type: `method`

Mantiene o rimuove i file caricati dopo la risposta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean` | no |  | `false` mantiene i file. |

I file caricati vengono rimossi quando la risposta termina. `$.autoclear(false)` li mantiene, per esempio quando li elabori più tardi.

### $.cancel()

Type: `method`

Interrompe l'elaborazione della richiesta in un evento.

Chiamalo in `ON('request', fn)` o `ON('controller', fn)` quando l'handler risponde da sé alla richiesta.

Example: Esempio
```js
ON('request', function($) {
	if ($.url === '/health/') {
		$.cancel();
		$.plain('OK');
	}
});
```

### HttpFile

Type: `class`

Un file caricato in `$.files`.

Proprietà: `name` (il campo del form), `filename`, `type` (il content type), `size` (byte), `extension`, `width` e `height` (immagini), `path` (il file temporaneo), e `isImage`, `isVideo`, `isAudio`.

Metodi:

- `move(filename, [callback])` (anche `rename()`) sposta il file; senza callback restituisce una `Promise`. Un file spostato non viene rimosso dopo la risposta.
- `copy(filename, callback)` copia il file.
- `read([callback])` legge il file in un `Buffer`; senza callback restituisce una `Promise`.
- `md5([callback])` calcola l'hash MD5 in esadecimale; senza callback restituisce una `Promise`.
- `stream([opt])` restituisce uno stream di lettura; `pipe(stream, [opt])` invia il file in uno stream tramite pipe.
- `image([shell])` restituisce un oggetto immagine per [Immagini](../../guides/images/).
- `fs(storage, id, [callback])` salva il file in un [file storage](../../guides/file-storage/).

Example: Salvare in un file storage
```js
ROUTE('POST /upload/ <10MB', function($) {
	var file = $.files[0];
	file.fs('files', UID(), function(err, meta) {
		if (err)
			$.invalid(err);
		else
			$.success(meta.id);
	});
});
```
