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

# Controller

> Il controller è `this` in ogni azione di una route: contiene i dati della richiesta e risponde alla richiesta.

Ogni azione di una route viene eseguita con un **controller** come `this`. Il controller contiene i dati della richiesta e ha i metodi che le rispondono. Per ogni richiesta viene creato un nuovo controller.

```js
exports.install = function() {
	ROUTE('GET /products/{id}/', detail);
};

function detail(id) {
	// id === this.params.id
	this.json({ id: id, ip: this.ip });
}
```

Le parti dinamiche dell'URL arrivano come argomenti dell'azione, nel loro ordine. L'elenco completo di proprietà e metodi è nel riferimento di [Controller](../../reference/controller/).

## Dati della richiesta

| Proprietà | Cosa contiene |
| --- | --- |
| `this.body` | Il corpo della richiesta già analizzato (JSON o un form) |
| `this.query` | La query string come oggetto (`?page=2` dà `{ page: '2' }`) |
| `this.params` | I parametri dinamici dell'URL, convertiti secondo il loro tipo (`{page:number}`) |
| `this.files` | I file caricati, per le route con il flag `upload` |
| `this.user` | L'utente che il tuo delegato `AUTH()` ha accettato, oppure `undefined` |
| `this.headers` | Gli header della richiesta, con i nomi in minuscolo |
| `this.ip` | L'indirizzo IP del client (il primo indirizzo di `X-Forwarded-For` dietro un proxy) |
| `this.url` | Il percorso dell'URL in minuscolo, con la barra finale |
| `this.uri` | L'URL analizzato (`pathname`, `query`, `hostname`…) |
| `this.ua` | Un nome breve del browser e del sistema, ricavato da `User-Agent` |
| `this.mobile`, `this.robot` | `true` per i dispositivi mobili, o per i crawler |
| `this.xhr` | `true` quando la richiesta ha `X-Requested-With: XMLHttpRequest` |
| `this.referrer` | L'header `Referer`, oppure una stringa vuota |
| `this.language` | La lingua impostata dal tuo delegato di localizzazione |
| `this.req`, `this.res` | Gli oggetti richiesta e risposta del framework |

```js
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact() {
	var model = this.body;
	var page = this.query.page;
	var agent = this.headers['user-agent'];
	this.success();
}
```

`this.query` e `this.body` contengono stringhe: converti tu numeri e date, oppure lascia che lo faccia uno schema (vedi [Routing](../routing/)).

## File caricati

Una route con il flag `upload` legge `multipart/form-data`. Ogni elemento di `this.files` ha `name` (il campo), `filename`, `type`, `size`, `extension`, e `width` e `height` per le immagini. `move()`, `copy()` e `read()` restituiscono una promise quando non passi una callback:

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

async function upload() {
	var file = this.files[0];
	if (!file || !file.isImage()) {
		this.invalid('Send an image');
		return;
	}
	await file.move(PATH.public('photos/' + file.filename));
	this.success();
}
```

Il framework rimuove i file temporanei quando la richiesta termina. Chiama `this.autoclear(false)` per conservarli.

## Rispondere

Rispondi a ogni richiesta **una sola volta**. I metodi restituiscono il controller, quindi puoi chiamare `return this.json(...)` per fermare l'azione.

| Metodo | Risposta |
| --- | --- |
| `this.json(obj)` | JSON (`application/json`) |
| `this.plain(text)` | Testo semplice; un oggetto viene serializzato come JSON formattato |
| `this.html(body)` | HTML |
| `this.content(body, type)` | Qualsiasi testo con il tuo content type |
| `this.view(name, [model])` | Una vista renderizzata da `views/` |
| `this.file(filename, [download])` | Un file da `public/` (o qualsiasi percorso che inizia con `~`) |
| `this.binary(buffer, type)` | Un buffer |
| `this.stream(stream, type)` | Uno stream leggibile |
| `this.redirect(url, [permanent])` | Un redirect, `302` o `301` |
| `this.empty()` | Un corpo vuoto |
| `this.nocontent()` | `204 No Content` |
| `this.success([value])` | `{ "success": true }` |
| `this.invalid(error)` | Un errore come JSON, `400` per impostazione predefinita |

```js
function download() {
	this.file('invoices/2024.pdf', 'invoice.pdf');
}

function legacy() {
	this.redirect('/new-address/', true);
}
```

## Il codice di stato

Imposta `this.status` prima di rispondere. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` ed `empty()` lo usano; il valore predefinito è `200`.

```js
function create() {
	var item = { id: UID(), name: this.body.name };
	this.status = 201;
	this.json(item);
}
```

`this.empty(204)` imposta lo stato e risponde in una sola chiamata.

## Successo ed errori di validazione

`this.success()` risponde `{ "success": true }`. Con un valore risponde `{ "success": true, "value": ... }`, e `this.success(false)` risponde `{ "success": false }`.

`this.invalid()` risponde con un array di errori come JSON e con lo stato `400`. Un numero come primo argomento imposta un altro stato:

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

Due helper creano callback nello stile `(err, response)`. `this.done()` risponde `invalid(err)` in caso di errore e `success()` altrimenti; `this.done(true)` aggiunge la risposta come `value`. `this.callback()` risponde con la risposta come JSON, oppure con una vista quando passi il suo nome:

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

function remove() {
	removeproduct(this.params.id, this.done());
}
```

## Pagine di errore

`this.throw404()` e i suoi simili rispondono con una pagina di errore: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` e `throw503()`. Hanno degli alias chiamati `view400()`… `view503()`. L'argomento è una descrizione del problema; `throw500(err)` registra anche l'errore nel log.

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

Per renderizzare una tua pagina, dichiara una route per lo stato. Il problema si trova in `this.exception`:

```js
exports.install = function() {
	ROUTE('#404', notfound);
};

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

Senza una route di questo tipo il framework renderizza la propria pagina di errore.

## Header e cache

`this.header(name, value)` imposta un header della risposta. La maggior parte dei metodi di risposta accetta anche un oggetto con gli header. `this.nocache()` disattiva la cache HTTP della risposta:

```js
function report() {
	this.nocache();
	this.header('X-Report', 'daily');
	this.plain('...');
}
```

## Cookie

`this.cookie(name)` legge un cookie. `this.cookie(name, value, expires, [options])` lo scrive; `expires` è un testo come `'5 days'`, e le opzioni sono `domain`, `path` (`/`), `secure`, `httponly` e `samesite` (`Lax` per impostazione predefinita):

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

function logout() {
	this.cookie('session', '', '-1 day');
	this.redirect('/');
}
```

## Viste e layout

`this.view(name, [model])` renderizza `views/name.html` dentro il layout `views/layout.html`. Le route di `controllers/default.js` trovano le loro viste in `views/`; le route di un altro controller, per esempio `controllers/admin.js`, in `views/admin/`. Un nome che inizia con `~` parte sempre da `views/`.

```js
function home() {
	this.layout('layout_home');
	this.title('Welcome');
	this.view('index', { products: [] });
}
```

- `this.layout(name)` sceglie un altro layout; `this.layout('')` renderizza la vista senza layout.
- `this.title()` e `this.meta(title, [description], [keywords], [image])` impostano valori che il layout stampa con `@{title}` e `@{meta}`.
- `this.repository` è un oggetto condiviso dalla vista e dal suo layout.
- `this.view(name, model, true)` restituisce l'HTML come stringa invece di rispondere.

La sintassi dei template è spiegata in [Viste](../views/).

## Utenti autenticati

`this.user` è ciò che il tuo delegato `AUTH()` ha accettato. Le route con `+` vengono eseguite solo per gli utenti autenticati, quindi lì `this.user` esiste sempre:

```js
// definitions/auth.js
AUTH(function($) {
	var token = $.cookie('session');
	if (token === 'token')
		$.success({ id: 1, name: 'Peter' });
	else
		$.invalid();
});

// controllers/default.js
exports.install = function() {
	ROUTE('+GET /account/', account);
};

function account() {
	this.json(this.user);
}
```

## Errori nelle azioni

Un'eccezione lanciata in un'azione viene registrata nel log e la richiesta riceve la pagina di errore `500`. Nelle callback e nelle promise nessuno cattura l'eccezione al posto tuo: catturala e chiama `this.throw500(err)` o `this.invalid(err)`.

```js
async function stats() {
	try {
		var data = await loadstats();
		this.json(data);
	} catch (err) {
		this.throw500(err);
	}
}
```
